Why would you make a destructor virtual?
Answer Posted / chandra sekhar
what chandra said is correct.but it is not 100% correct.for
that answer i want to add one point.
whenever
1)there is a pointer in the base class and we allocated
with the help of new in base class and anthoer pointer in
derived class and agin we allocated with the help of new.
2)whenever the base class object pointer points to
derived class object,and is being created using new.
i.e class base - base class
in main - base bptr;
class derived - derived class
in main - bptr = new derived();
this will be illustrated with an example given below
#include <iostream.h>
class Base
{ protected:
int *ptr;
public:
Base()
{ ptr = new int[10];
cout<<"Constructor: Base"<<endl;
}
virtual ~Base()
{
cout<<"Destructor : Base"<<endl;
delete []ptr;
}
};
class Derived: public Base
{
protected:
int *ptr1;
public:
Derived()
{
ptr1=new int[10];
cout<<"Constructor: Derived"<<endl;
}
~Derived()
{
delete []ptr1;
cout<<"Destructor : Derived"<<endl;
}
};
void main()
{
Base *Var = new Derived;
delete Var;
}
if we are not placing virtual in base class, only base
class destructor will be called because "var is of type
Base".so,
if we are not placing virtual compiler will see only "type
of the pointer,not the object which it is holding".so,if we
place virtual it will see the object it is holding.
now memory allocated for ptr,ptr1 in heap was destroyed by
destructors of the respective class.
| Is This Answer Correct ? | 4 Yes | 0 No |
Post New Answer View All Answers
How can I learn c++ easily?
What is the type of this pointer in c++?
When is the copy constructor called?
Define what is constructor?
What are libraries in c++?
Is vector a class in c++?
. If employee B is the boss of A and C is the boss of B and D is the boss of C and E is the boss of D. Then write a program using the Database such that if an employee name is Asked to Display it also display his bosses with his name. For eg. If C is displayed it should also display D and E with C?
What information can an exception contain?
What is c++ manipulator?
Describe the setting up of my member functions to avoid overriding by the derived class?
Using a smart pointer can we iterate through a container?
How to give an alternate name to a namespace?
Describe the advantages of operator overloading?
What is fflush c++?
What is the operator in c++?