Virtual Destructors
We might deletea pointer to the base type that actually points to a derived object.If we deletea pointer to base, then the base-class destructor is run and the members of the base are cleaned up.If the object really is a derived type, then the behavior is undefined.To ensure that the proper destructor is run, the destructor must be virtual in the base class:
class Item_base {
public:
// no work, but virtual destructor needed
// if base pointer that points to a derived object is ever deleted
virtual ~Item_base() { }
};
If the destructor is virtual, then when it is invoked through a pointer, which destructor is run will vary depending on the type of the object to which the pointer points:
Item_base *itemP = new Item_base; // same static and dynamic type
delete itemP; // ok: destructor for Item_base called
itemP = new Bulk_item; // ok: static and dynamic types differ
delete itemP; // ok: destructor for Bulk_item called
Like other virtual functions, the virtual nature of the destructor is inherited. Therefore, if the destructor in the root class of the hierarchy is virtual, then the derived destructors will be virtual as well.A derived destructor will be virtual whether the class explicitly defines its destructor or uses the synthesized destructor.
Destructors for base classes are an important exception to the Rule of Three .That rule says that if a class needs a destructor, then the class almost surely needs the other copy-control members.A base class almost always needs a destructor so that it can make the destructor virtual. If a base class has an empty destructor in order to make it virtual, then the fact that the class has a destructor is not an indication that the assignment operator or copy constructor is also needed.
Best Practices :The root class of an inheritance hierarchy should define a virtual destructor even if the destructor has no work to do.
Constructors and Assignment Are Not Virtual
Of the copy-control members, only the destructor should be defined as virtual. Constructors cannot be defined as virtual. Constructors are run before the object is fully constructed. While the constructor is running, the object's dynamic type is not complete.
Making the assignment operator virtual is likely to be confusing because a virtual function must have the same parameter type in base and derived classes. The base-class assignment operator has a parameter that is a reference to its own class type. If that operator is virtual, then each class gets a virtual member that defines an operator=that takes a base object. But this operator is not the same as the assignment operator for the derived class.
Beware:Making the class assignment operator virtual is likely to be confusing and unlikely to be useful.