Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it recommended to explicitly make overriding functions virtual?

In times before C++11 when a virtual function was overriden in a derived class, it was recommended to add the virtual keyword also to the derived class function to make the intention clear.

Nowadays such a function is marked "override" which kind of includes the notion that there must be a virtual base function. Therefore I am now preferring to omit the virtual:

class Derived: public Base {
public:
  void Overriden() override;
  // Instead of: virtual void Overriden() override;
};

However this leads to an IntelliSense error in MSVC 2012: the 'override' modifier requires a virtual function declaration with an explicit 'virtual' keyword

Obviously the compiler compiles the class, but the error makes me think about it. Are there still valid reasons to add the virtual keyword?

like image 939
Kit Fisto Avatar asked Sep 12 '13 13:09

Kit Fisto


Video Answer


2 Answers

as reported in the documentation for the override keyword, its meaning is that the function at hand MUST override a virtual function:

In a method declaration, override specifies that the function must be overriding a base class method.

It is a mean for enforcing (i.e. making the compiler enforce) such requirement. Of course, if the base class' function is not virtual, the code won't compile. Hence, as you pointed out, adding virtual is redundant.

I would argue that it was not good advice to add it before c++11 either. Consider this snippet of code:

#include <iostream>

using namespace std;

class A{
    public:
    void f(){
        cout << "A" << endl;
    }
};

class B : public A{
    public:
    virtual void f(){
        cout << "B" << endl;
    };
};

class C : public B{
    public:
    void f(){
        cout << "C" << endl;
    };
};

int main( int argc, char* argv[] ) 
{
    C c;
    A& aref = c;
    aref.f();
    B& bref = c;
    bref.f();
}

whose output is, clearly, "A" followed by "C". As you see, adding virtual in class C would have no effect at all, while the virtual in class B plays a key role. Adering to the convention of adding virtual to class C would make this harder to see at a glance.

like image 172
Stefano Falasca Avatar answered Oct 14 '22 15:10

Stefano Falasca


I think this is more a question of taste :-)

I prefer to only write override behind the definition which implies that the function is already virtual. Programmers are lazy by definition, so keep the source short :-)

We had add a rule to our coding guidelines where override is a must and the virtual should be removed from old code during normal change process or while refactoring the actual class.

But this is only our solution and there is no technical reason for this!

like image 30
Klaus Avatar answered Oct 14 '22 14:10

Klaus