keyword virtual before overriding function in Derived class

Jul 13, 2011 at 3:38pm
Hi:

In terms of OOP with C++, consider:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Base
{
public:
  virtual void print ()
  {
     cout << "Base::print" << endl;
  }
};

class Derived : public Base
{
public:
  void print () // should we add key word "virtual" here?
  {
     cout << "Derived::print" << endl;
  }
};



Functionally, it doesn't matter at all whether we add "virtual" or not, because either way, the print() function in Derived class is a virtual function.

So in order to follow good practice/OOP programming style, should we add "virtual" and WHY('why' is important to me :))?

Thanks in advance!
Jul 13, 2011 at 4:18pm
Since functionality reasons are out of the equation (because it works with or without it), you just have to consider other areas that may or may not be important to you (or others that work with you). In my case I consider important to write clear, self-explained code. I therefore add the virtual keyword even when it is not needed to make it easier to find vtable functions.
Jul 13, 2011 at 4:29pm
No, you shouldn't repeat virtual. However, you should use override:
1
2
3
4
void print() override
{
  //...
}


This not only tells the reader that print() is virtual, it also prevents mistakes where you accidentally change the function signature (such as adding or forgetting a const), which would normally cause the function not to be overridden without generating a compiler error or even a warning.
However, note that explicit overriding is a C++11 feature.
Jul 13, 2011 at 4:53pm
@all

Guys, thanks for the inputs!

My compiler supports override, which is handy. Thanks, Athar.
Topic archived. No new replies allowed.