4

I really like the new override keyword of c++11 and i am trying to add it to my code everywhere. It would be nice if the compiler would help me spot all of these cases.

Is there any way to make the compiler behave as if the override keyword is mandatory? I am using visual studio 2012

For example, I want the compiler to emit an error/warning:

class Base{
public:
    virtual void the_virtual(){}
};
class derive:public Base{
public:
    void the_virtual(){} //warning/error wanted here
};
tecywiz121
  • 169
  • 1
  • 7
yigal
  • 3,923
  • 8
  • 37
  • 59
  • Did you look at the "similar questions" suggestions before posting this question?! This has been asked before on more than one occasion. – Kerrek SB Jan 11 '14 at 15:13
  • I'd really hate to get a warning (or even worse, an error) just because I did what you wrote. – Moo-Juice Jan 11 '14 at 15:14
  • Add some point during the C++0x standardisation process you could used to write `class Dervied explicit : public Base` to achieve this. – Simple Jan 11 '14 at 15:49
  • 1
    possible duplicate of [How to enforce the 'override' keyword?](http://stackoverflow.com/questions/13223277/how-to-enforce-the-override-keyword) – Gabriel L. Jan 11 '14 at 16:20
  • There is also some buildup in gcc community. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2852.html – KRoy Dec 04 '17 at 23:13

1 Answers1

3

I would start with the basics and give the class a virtual destructor: compilers tend to warn about that.

With respect to the actual question, it is highly unlikely that the use of override will be made mandatory as there is way too much code in existence which would need to get patched up. The general view taken by the standards committee on issues like these is that it is a quality of implementation issue: compilers are entirely free to warn about all sorts of potentially problematic declaration. That is, you'd lobby your compiler vendor or your static analyzer vendor to create a warning for this situation. ... and if you don't think you can make the vendors apply the check, create it yourself! Checking whether there is an override keyword when overriding a virtual function using, e.g., clang is fairly simple.

Also, here is an example where a mandatory use of override would not work:

struct Base1 {
    virtual ~Base1() {}
    virtual int f() { return 0; }
};
struct Base2 {
    int f() { return 1; }
};

template <typename Base>
struct Derived: Base { 
    int f() { return 2; }
};

int main()
{
    Derived<Base1> d1;
    Derived<Base2> d2;
}

In the class template Derived the function f() may or may not be an override. You can't conditionally put override there.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380