30

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 ?

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
ereOn
  • 53,676
  • 39
  • 161
  • 238
  • 4
    Note to readers: also take a look at the [`override`](http://stackoverflow.com/questions/13880205/override-in-c11) keyword in C++11 which is closely related to that topic. – ereOn Jun 12 '14 at 06:57

3 Answers3

39

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.

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
10

You do not need it, but marking it so may make your code clearer.

Note: if your base class has a virtual destructor, then your destructor is automatically virtual. You might need an explicit destructor for other reasons, but there's no need to redeclare a destructor simply to make sure it is virtual. No matter whether you declare it with the virtual keyword, declare it without the virtual keyword, or don't declare it at all, it's still virtual.

- C++ FAQ - When should my destructor be virtual?

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
JRL
  • 76,767
  • 18
  • 98
  • 146
7

Virtual is automatically picked up on derived method overrides regardless of whether you specify it in the child class.

The main consequence is that without specifying virtual in the child it's harder to see from the child class definition that the method is in fact virtual. For this reason I always specify virtual in both parent and child classes.

Mark B
  • 95,107
  • 10
  • 109
  • 188