If the destructor of the base class is not declared as virtual, the derived class may not be correctly destroyed in some scenarios. Use the following code as an example:
#include<iostream>
using namespace std;
class base {
public:
base()
{ cout << "in base()" << endl; }
~base()
{ cout << "in ~base()" << endl; }
};
class derived : public base {
public:
derived()
{ cout << "in derived()" << endl; }
~derived()
{ cout << "in ~derived()" << endl; }
};
int main(void)
{
base *b = new derived();
delete b;
return 0;
}
The output of the program:
in base()
in derived()
in ~base()
The destructor of the derived class is not called.
When we change the destructors to virtual:
#include<iostream>
using namespace std;
class base {
public:
base()
{ cout << "in base()" << endl; }
virtual ~base()
{ cout << "in ~base()" << endl; }
};
class derived : public base {
public:
derived()
{ cout << "in derived()" << endl; }
virtual ~derived()
{ cout << "in ~derived()" << endl; }
};
int main(void)
{
base *b = new derived();
delete b;
return 0;
}
The output of the program is changed to:
in base()
in derived()
in ~derived()
in ~base()
Tuesday, May 7, 2019
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment