Is there a use for making a protected destructor virtual?

后端 未结 4 1091
天命终不由人
天命终不由人 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:27

    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.

提交回复
热议问题