destructor snafu
I was writing code in C++ today and I had this bug I couldn''t figure out. The details are not important, but let''s just say I was very confused. Finally I isolated the error down to a destructor for a particular subclass not being called. And I made a valuable discovery. Take the program below:
#include
#include
class Base
{
public:
Base() { cout << "constructing base" << endl; }
~Base(){ cout << "destructing base" << endl; }
};
class Sub : public Base
{
public:
Sub(){ cout << "constructing sub" << endl; }
~Sub(){ cout << "destructing sub" << endl; }
};
int main()
{
Base* TheClass;
TheClass = new Base;
delete TheClass;
cout << "\n";
TheClass = new Sub;
delete TheClass;
system("PAUSE");
return 0;
}
Now, you would expect this to output this:
constructing base
destructing base
constructing base
constructing sub
destructing sub
destructing base
But instead, (and I''ve tried this on two compilers) you get this:
constructing base
destructing base
constructing base
constructing sub
destructing base
The destructor for the subclass never gets called! I was shocked, but it does this on both Visual C++ and Dev-C++. Is there any way to get around this problem? Any other function you can declare to be virtual, but evidently not the destructor. Is it just me, or does this not seem terribly limiting? Is anyone else surprised by this as much as I am? I even tried making a virtual function called destroy() with different implementations in the base class and subclass, and calling it from the base class destructor, but this did not work either- it always calls the version of destroy() from the base class. Anybody know of another possible workaround?
"The reasonable man adapts himself to the world, butthe unreasonable man tries to adapt the world to him-therefore, all progress depends on the unreasonable man." -Samuel Butler
Add ''virtual'' before the destructor for Base.
Martee
Magnum Games.NET
All your code are belong to us.
Martee
Magnum Games.NET
All your code are belong to us.
ReactOS - an Open-source operating system compatible with Windows NT apps and drivers
March 03, 2001 06:57 PM
very simple...
your derived class has to have a virtual destructor, otherwise it wont be called.
virtual ~Derived() {}
your derived class has to have a virtual destructor, otherwise it wont be called.
virtual ~Derived() {}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement