Virtual Destructors in C++
Hi All,
I have just started looking seriously into C++. One concept that I still need more explaination on is the use of Virtual destructors in case of polymorphism and inheritance.
Could some kind sould please enlighten me as to the exact use and functionalities of declaring destructors as virtual in a base class?
Thanks for the time
Cheers
[379 byte] By [
prahaladd] at [2007-11-11 10:21:21]

# 1 Re: Virtual Destructors in C++
declaring destructor virtual in base class ensures that when a derived class object is destroyed, proper destructor is called.
# 2 Re: Virtual Destructors in C++
Example:
struct A
{
int x;
~A(cout<<"A destroyed"<<endl;); //nonvirtual
};
struct B: A //inheriting from a class that has a non-virtual dtor. very bad idea!
{
int y;
~B(cout<<"B destroyed"<<endl;);
};
Now try to run the following code:
int main()
{
A* p = new B;
delete p;
}
Next, change the dtor of A to virtual and run the same code once more. Can you see the difference?
Danny at 2007-11-11 20:59:58 >
