Virtual Keyword Alert

I recently had a nasty problem that boiled down to a very simple coding error. Consider the following code:

#include <iostream> class Base { public: void func() { std::cout << "BASE" << std::endl; } }; class Derived : public Base { public: virtual void func() { std::cout << "DERIVED" << std::endl; } }; int main(int argc, char* argv[]) { Base* obj = new Derived; obj->func(); delete obj; return 0; } 

Output signal

BASE

Obviously (for this case) I wanted to put the virtual keyword on Base :: func so that Derived :: func is called basically. I understand that this is (possibly) allowed by the C ++ standard and, possibly, with good reason, but it seems to me that in 99% of cases this would be a coding error. However, when I compiled using g ++ and all the -Wblah options that I could think of, there were no warnings.

Is there a way to generate a warning when the base and derived classes have member functions with the same name, where the derived class function is virtual and the base class function is not?

+7
c ++ g ++
source share
3 answers

In Visual C ++, you can use the override extension. Like this:

 virtual void func() override { std::cout << "DERIVED" << std::endl; } 

This will give an error if the function does not actually override the base class method. I use this for ALL virtual functions. I usually define a macro as follows:

 #ifdef _MSC_VER #define OVERRIDE override #else #define OVERRIDE #endif 

Therefore, I can use it as follows:

 virtual void func() override { std::cout << "DERIVED" << std::endl; } 

I was looking for something similar in g ++, but could not find a similar concept.

The only thing I don't like about Visual C ++ is that you cannot force the compiler (or at least warn) the compiler to execute all overridden functions.

+5
source share

I don’t know of a single g ++ flag for creating a warning about this (not to say that it does not exist), but I would say that this is a rather rare error. Most people first write the base class as an interface using pure virtual functions. If you would say:

 void func() = 0; 

then you will get a syntax error.

+3
source share

man gcc

-Woverloaded-virtual (C ++ and Objective-C ++ only) Warn when a function declaration hides virtual functions from the base class. For example, in:

  struct A { virtual void f(); }; struct B: public A { void f(int); }; the "A" class version of "f" is hidden in "B", and code like: B* b; b->f(); will fail to compile. 
+1
source share

All Articles