Jump to content
  • Advertisement
Sign in to follow this  
digitalfreak

virtual destructor?

This topic is 5033 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

to override a normal virtual function of a base class in a sub class, the function's names have to be the same; but destructor is an exception coz destructor's name has to be the same with the class name, is it so? if I don't define a destructor in sub class, is its parents' destructor inherited or does the compliler instert an empty one for it like it does for constructor?

Share this post


Link to post
Share on other sites
Advertisement
Yes, it's inherited in that case.

You must, however, define destructors in base classes as 'virtual'. Otherwise the wrong destructor is called.

class A
{
virtual ~A();
}
class B : public A
{
~B();
}

A *b = new B;
delete b;
If A is not virtual the compiler will call ~A() instead of ~B() when b is deleted.

Share this post


Link to post
Share on other sites
Every class has an implicit destructor (base and derived).
However the base destructor is always called from the explicit or implicit derived class destructor.


class Base
{
public:
~Base(){
...
}
};

class Derived: public Base
{
public:
~Derived(){
...
}
};



When you destroy a Derived object it is called ~Derived() and then ~Base().
Note that ~Base() is always called also if you dont provide ~Derived() explicitly.
When you derive a class, the base destructor is virtual for definition...but it is a good practice to declare it as virtual if you plan to derive the class.

See also
http://www.parashift.com/c++-faq-lite/dtors.html

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!