• Pointer is of type Base class and object created using ‘new’ operator is of type Derived class. So, at the time of object creation, constructor invocation is from Base class to Derived class.
• But while deleting pointer Base, compiler cannot tell that Derived class instance is destroyed. Note that ‘delete’ calls the destructor for the class.
•This problem can be solved by declaring the destructor of the base class as ‘virtual’. In this way, the destructor will be invoked through virtual function table.
#include<iostream.h>
class Base
Output:
Base:Constructor
Derived:Constructor
Base:Destructor
After changing Base class destructor as below:
virtual ~Base()
• But while deleting pointer Base, compiler cannot tell that Derived class instance is destroyed. Note that ‘delete’ calls the destructor for the class.
•This problem can be solved by declaring the destructor of the base class as ‘virtual’. In this way, the destructor will be invoked through virtual function table.
Example:
class Base
{ public:
Base()
{
cout<<“Base:Constructor”<<endl;
}
~Base(){
~Base(){
cout<<“Base:Destructor”<<endl;
}
};
class Derived:public Base
{
Derived(){
};
class Derived:public Base
{
Derived(){
cout<<“Derived:Constructor”<<endl;
}
~Derived(){
~Derived(){
cout<<“Derived:Destructor”<<endl;
}
};
main()
};
main()
{
Base *base=new Derived;
Base *base=new Derived;
delete base;
}
Base:Constructor
Derived:Constructor
Base:Destructor
After changing Base class destructor as below:
virtual ~Base()
{
cout<<“Base:Destructor”<<endl;
}
Output:
Base:Constructor
Derived:Constructor
Derived:Destructor
Base:Destructor
Output:
Base:Constructor
Derived:Constructor
Derived:Destructor
Base:Destructor
No comments:
Post a Comment