/*Child is inherited from Parent*/
class Parent {
public:
Parent () //Constructor
{
cout << \"\\n Parent constructor called\\n\" <<
Yes, if you intend to do delete this
in class Parent
member functions which is very common when implementing IUnknown::Release()
in COM objects.
Just to give one example: Say you have an base class which implements reference counting. You have an addRef
and a release
method and you want your object to be destroyed, if (and only if) the internal counter reaches zero through a call to release
.
So, first you want your destructor protected (since you only want to destroy the object from within relase
).
If you plan to derive from your class, you also want to have your destructor virtual, since you need a virtual destructor whenever you want to destroy a child object through a pointer to a base class (thanks @sharptooth for the hint ...)
There's an entry in the C++ Core Guidelines dedicated to this specific subject:
C.35: A base class destructor should be either public and virtual, or protected and nonvirtual
Reason To prevent undefined behavior. If the destructor is public, then calling code can attempt to destroy a derived class object through a base class pointer, and the result is undefined if the base class’s destructor is non-virtual. If the destructor is protected, then calling code cannot destroy through a base class pointer and the destructor does not need to be virtual; it does need to be protected, not private, so that derived destructors can invoke it. In general, the writer of a base class does not know the appropriate action to be done upon destruction.
So, the destructor doesn't need to be virtual if it's protected. However, there is an exception:
Exception We can imagine one case where you could want a protected virtual destructor: When an object of a derived type (and only of such a type) should be allowed to destroy another object (not itself) through a pointer to base. We haven’t seen such a case in practice, though.
So, to sum up, in practice a protected destructor does not need to be virtual.
protected: Base::~Base();
should be virtual at least if you (plan on) deleting any objects derived from Base
within Base
or a derived class of Base
.