class Base
{
public:
virtualvoid 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 :))?
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.
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.