Jump to content
  • Advertisement
Sign in to follow this  
DarkRadeon

C++ inheritance: virtual destructor or protected destructor?

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

I have a class. It could probably inherited or maybe not.. that's not so important for now... Well, since I want to write a little framework in the feature I think it could be derived...

Anyway, the question is if it is a better programming choice tu use a virtual destructor allowing inherited destructor or a protected destructor and giving the derived class the job to write a totally new destructor. I think that the virtual is the better, but I'm not sure about that.

In another case I will make a static member function to create the object, so shall make the destructor protected (and virtual if I want to allow derived classes) ?

Share this post


Link to post
Share on other sites
Advertisement
Inherit to be reused, not to reuse.

If a protected destructor is the solution to your problem then you have solved the wrong problem.

Share this post


Link to post
Share on other sites
Hidden
The point of having your destructor virtual is that you want the right destructor to be called when you call "delete" on it.

Example:

class A {
};

class B : public A {
};

A* baseptr = new B();
delete baseptr; // This line will call A:s destructor unless A has declared its destructor virtual, resulting in a potetial memory leak


I'm not really sure what the point would be of making a destructor protected...
I guess that would mean that only the object itself can delete itself, sounds a bit... wonky. (probably useful in some special case, but not often...)

Share this post


Link to post
I wouldn't go as far as to say any. Traits classes used in metaprogramming (which generally just include a set of typedefs) are often intended to be derived from, but don't need to have a virtual destructor. An example from the standard library is std::unary_function. Examples from outside the standard library often will have a protected destructor to indicate that you shouldn't delete object through that base type.

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.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!