Is there a use for making a protected destructor virtual?

后端 未结 4 1121
天命终不由人
天命终不由人 2021-01-11 15:46
/*Child is inherited from Parent*/
class Parent {  
  public:  
    Parent () //Constructor
    {
        cout << \"\\n Parent constructor called\\n\" <<         


        
4条回答
  •  庸人自扰
    2021-01-11 16:26

    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 ...)

提交回复
热议问题