Click to See Complete Forum and Search --> : Quick Destructor Question
Bob Davis
September 4th, 2002, 12:19 AM
A quick question that should have a simple answer:
I know that when you construct an object that inherits from another class, the parent class(es) constructors' are called to construct their portion of the object. My question is, when the destructor for the object is called, does it call the parent class(es) destructors also? And, does making the destructor virtual affect this behavior?
NigelQ
September 4th, 2002, 12:23 AM
If you make the derived class' destructor virtual, the base class destructor will be called, otherwise the base class' destructor will not be called.
Therefore, all derived class' destructors should be declared virtual unless you really don't want to call the base class destructor.
Hope this helps,
- Nigel
AnthonyMai
September 4th, 2002, 12:55 AM
Nigel, you need to get your facts straight. Your answer wouldn't get you pass too many job interviews for jonior programmers.
A derived class destructor will surely call destructor of its base class as well as destructors of all its members, regardless whether the destructor was declared virtual or none-virtual.
The only case this may be a bit tricky is when virtual inheritance and multiple inheritance is involved.
cup
September 4th, 2002, 04:03 AM
It really depends on how you call the dtor of the derived class. If you call the dtor of the derived class directly, then it will call the dtor of the derived class and the base class. However, if you call it from the base class, it only knows about the base class and not about the derived class. Try the following.
#include <iostream>
using namespace std;
class Base
{
public:
~Base ()
{
cout << "Base destroyed" << endl;
}
};
class DBase: public Base
{
public:
~DBase ()
{
cout << "Dbase destroyed" << endl;
}
};
class VBase
{
public:
virtual ~VBase ()
{
cout << "VBase destroyed" << endl;
}
};
class DVBase: public VBase
{
public:
~DVBase ()
{
cout << "DVBase destroyed" << endl;
}
};
int main()
{
Base* aaa = new DBase ();
DBase* bbb = new DBase ();
VBase* ccc = new DVBase ();
DVBase* ddd = new DVBase ();
cout << endl << "deleting base" << endl;
delete aaa;
cout << endl << "deleting dbase" << endl;
delete bbb;
cout << endl << "deleting vbase" << endl;
delete ccc;
cout << endl << "deleting vdbase" << endl;
delete ddd;
return 0;
}
Output
deleting base
Base destroyed
deleting dbase
Dbase destroyed
Base destroyed
deleting vbase
DVBase destroyed
VBase destroyed
deleting vdbase
DVBase destroyed
VBase destroyed
When deleting aaa, it doesn't know anything about Dbase because the dtor is not virtual. However, when deleting ccc, it destroys DVBase as well.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.