Search code examples
c++virtual-destructor

No virtual functions, but still need virtual destructor?


I wrote a base and derived class that had no virtual functions. The use of virtual is typically the guide I see for when to use a virtual destructor.

However, while my classes have no virtual functions I am using the classes in a polymorphic way when I pass them around. Therefore, class Base should implement a virtual destructor?

class Base;
class Derived;

main()
{
   base& baseVar = derived();
   foo(baseVar);
}

Solution

  • There is no polymorphism because you call (will call) non-virtual functions using the referemce. That is in your example you simply call (will call) functions of the base class.

    Moreover this statement

    base& baseVar = derived();
    

    should not be compiled because you bind a temporary object with a non-const reference.

    There must be

    const base& baseVar = derived();
    

    As for the destructor in your example then there is no need to have a virtual destructor. Becasue you defined a reference to a temporary object of the derived class. In this case for the temporary object will be called its own destructor. That is at first the destructor of the base class will be called (from the destructor of the derived class) and then the body of the destructor of the derived class will be executed.

    The vertual destructor would be need if you would allocate a derived memory in the heap and assign the address of the allocated memory to a pointer of the base class. And when you would call operator delete for this pointer then if you have no virtual destructor then the only destructor of the base class would be called.

    For example

    class Base;
    class Derived;
    
    main()
    {
       base* baseVar = new derived();
       delete baseVar; // base shall have a virtual destructor
    }