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) ?
C++ inheritance: virtual destructor or protected destructor?
Inherit to be reused, not to reuse.
If a protected destructor is the solution to your problem then you have solved the wrong problem.
If a protected destructor is the solution to your problem then you have solved the wrong problem.
The point of having your destructor virtual is that you want the right destructor to be called when you call "delete" on it.
Example:
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...)
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...)
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement