Sign in to follow this  

the case of virtual destructors

This topic is 2666 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

hello all!

As everyone who ever read the 55 C++ commandments of Scott Meyer knows, "thou shalt write a virtual destructor for a base class intended to be used polymorphicaly."

the question is: what these virtual destructors should contain. I'm working through some code where the guy created the base classes defining an empty virtual destructor like


class X {
virtual ~X(){};
}


and now I need to use this X class. But what should I write in its destructor method? The implementation, I mean:



class D : public X{
virtual ~D();
}

D::~D() {
?????????????????????????????
}



D class will not need to free any acquired resource (think RAII), but I dunno what an empty destructor is worth for. Will D's own resources be released that way? Do I need to declare/define D's destructor anyway?




Share this post


Link to post
Share on other sites
If you don't need to do anything in D's destructor, you don't need to write it. The fact that X's destructor is virtual is enough.

Share this post


Link to post
Share on other sites
Quote:
Original post by SiCrane
If you don't need to do anything in D's destructor, you don't need to write it. The fact that X's destructor is virtual is enough.


cool!
And the empty virtual destructor in the base class does not make any harm too, I guess?

Share this post


Link to post
Share on other sites
Quote:
Original post by draconar
Quote:
Original post by SiCrane
If you don't need to do anything in D's destructor, you don't need to write it. The fact that X's destructor is virtual is enough.


cool!
And the empty virtual destructor in the base class does not make any harm too, I guess?


I dont think so, its the default case for a function. If none of the children classes have their own destructor, it will use the base class'.

Share this post


Link to post
Share on other sites
That's the rule for normal functions, but constructors and destructors work slightly differently. If you don't define a destructor, the compiler will define a destructor specific to that class. The compiler defined destructor will call the destructors of the member variables in reverse order of construction and then call the destructors of any base classes.

Share this post


Link to post
Share on other sites

This topic is 2666 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this