C++ inheritance: virtual destructor or protected destructor?

Started by
3 comments, last by alvaro 12 years, 4 months ago
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) ?

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.

Stephen M. Webb
Professional Free Software Developer

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...)
Also, any class from which you expect to derive should have a virtual destructor.
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.
I stand corrected. My rule works for the subset of the language that I use.

This topic is closed to new replies.

Advertisement