Search code examples
c++virtual-destructor

Do I still need to have a virtual destructor for my derived class in this situation?


I have been reading Effective C++ 3rd Edition by Scott Meyers and in one of the chapters he says that any class with virtual functions should almost certainly have a virtual destructor. Now for my code below, the function someFunc does not need a virtual in the derived class. However, I decided to put it there to show semantics and for better readability. Since I put the virtual there, does it mean that the destructor in the derived class has to be virtual?

#include <iostream>
using namespace std;

class base
{

public:
    base(){...}
    virtual ~base(){...}

    virtual someFunc() = 0;

};

class derived1:public base
{

public:
    derived1(){...} 
    ~derived1(){...} //Does this need to be virtual?

    virtual someFunc(/*Implement the function*/); //I made this virtual just to show meaning

};

int main()
{

    base* b;
    b=new derived1;
    delete b; //Will this cause a memory leak?

}

Solution

  • It already is!

    The virtual keyword is implicit for your derived::someFunc, and for your derived::~derived, because both functions' base equivalents are marked virtual.

    So, you may write the keyword virtual on both, neither or just one. It doesn't matter: they will both be actually virtual regardless.