Reputation: 1
In Chapter 9 of Effective C++: 55 Specific Ways to Improve Your Programs and Designs (3rd Edition) by Scott Meyers, it has a section entitled Item 53: Pay Attention to compiler warnings. Meyers says that the following program should give a warning:
class B {
public:
virtual void f() const;
};
class D: public B {
public:
virtual void f();
};
And says:
The idea is for
D::f
to redefine the virtual functionB::f
, but there’s a mistake: in B, f is a const member function, but in D it’s not declared const. One compiler I know says this about that:warning: D::f() hides virtual B::f()
Too many inexperienced programmers respond to this message by saying to themselves, "Of course
D::f
hidesB::f
— that’s what it’s supposed to do!" Wrong. This compiler is trying to tell you that the f declared in B has not been redeclared in D; instead, it’s been hidden entirely (see Item 33 for a description of why this is so). Ignoring this compiler warning will almost certainly lead to erroneous program behavior, followed by a lot of debugging to discover something this compiler detected in the first place.
But my compiler doesn't give any warning, even with with -Wall
. Why doesn't my compiler (GCC) give a warning?
Upvotes: 0
Views: 119
Reputation: 249434
As "chris" points out, GCC will warn you if you use -Woverloaded-virtual
, though this is not enabled by -Wall -Wextra
. In any case you don't need the compiler to find this anymore, you can use C++11:
class B {
public:
virtual void f() const;
};
class D: public B {
public:
void f() override;
};
By specifying override
whenever you intend to override a virtual method, the compiler will give you an error (not just a warning) if you get the signature wrong.
Regarding -Woverloaded-virtual
, note that it warns about more than just const
: it will also warn if you define a new method with the same name and completely different parameters. This sort of thing happens in real codebases and can be quite intentional, so that's probably why this can't be enabled in any of the coarse-grained warning options. I guess a const
-only warning might be nice, but now that we have C++11 it seems less relevant.
Upvotes: 3