Destructors:
Virtual Destructor:
Why virtual destructor?
class Base
{
~Base(){}
};
class Derv:public Base
{
~Derv(){}
};
int main()
{
Base *ptr = new Derv;
delete ptr;
}
Consider the above example, where the destructor is not virtual. When the destructor get auto invoked for operation delete on base class pointer (ptr in our case) pointing to derived class (class Derv in our case) object, the compiler will statically bind the call to destructor of Base because compiler looks only at the type of the pointer(Base in this case) and not on type of its content( Derv in this case). So destructor of derived class Derv is never called.
To achieve the correct result as it would have been when you define a derived class object, you need to make the destructor to be virtual.
Making the destructor of Base virtual makes destructor of Derv also to be virtual.
Now the compiler will not bind destructor with operation delete of Base class pointer( ptr in our case) pointing to derived class object at compile time. It will be left and decided at run time depending content of the base class type pointer. So it calls destructor of Derv class. This in turn calls destructor of Base class.
Virtual constructor:
Constructors cannot be made virtual. As per the C++ standard,
A constructor shall not be virtual
GCC gives " error: constructors cannot be declared virtual ".
class A
{public:
virtual A(){}
virtual ~A(){}
};
The above code fails with compile error: constructors cannot be declared virtual
An Example:
#include<iostream>
using namespace std;
class base
{
public:
base()
{
cout<<"inside base const\n";
}
virtual ~base() //declaring destructor of base as virtual to call child class destructor implicitly when we delete pointer to the base class pointing to the newly created instance of child1 class.
{
cout<<"inside base class destructor"<<endl;
}
};
class child1:public base
{
public:
child1()
{
cout<<"inside child conts\n";
}
~child1()
{
cout<<"inside child class destructor"<<endl;
}
};
int main()
{
base *bptr=new child1;
delete bptr;
return 0;
}
Comments