Search code examples
c++inheritancevirtual-destructor

Do I need to specify virtual on the sub-classes methods as well?


This has probably been asked before on SO, but I was unable to find a similar question.

Consider the following class hierarchy:

class BritneySpears
{
  public:

    virtual ~BritneySpears();
};

class Daughter1 : public BritneySpears
{
  public:

    virtual ~Daughter1(); // Virtual specifier
};

class Daughter2 : public BritneySpears
{
  public:

    ~Daughter2(); // No virtual specifier
};

Is there a difference between Daughter1 and Daughter2 classes ?

What are the consequences of specifying/not specifying virtual on a sub-class destructor/method ?


Solution

  • No you technically do not need to specify virtual. If the base member function is virtual then C++ will automatically make the matching override member function virtual.

    However you should be marking them override, which ensures that it's virtual, and also that it overrides a member function in the base class. The method is virtual after all, and it makes your code much clearer and easier to follow by other developers.


    Note: prior to C++11, you could make the overriding member function just virtual, since override isn't available yet.