Reputation: 509
When I override a virtual function:
class Geoff
{
public:
virtual int getArea() { return 0; }
}
Should I specify 'virtual' again when I override it? Does it make any difference? I know both ways seem to work fine, just wondering if there's more to it than that.
class George : public Geoff
{
public:
virtual int getArea() { return x*y; }
}
Upvotes: 17
Views: 1591
Reputation: 106126
If you use C++11, you should use override
instead, which both documents that you're overriding a virtual function and checks that a matching virtual function exists in a base for overriding.
int getArea() override { return x*y; }
In C++03 it's a stylistic choice - put virtual
in if you feel it adds documentation value.
Upvotes: 26
Reputation: 19620
No, use override. (http://en.cppreference.com/w/cpp/language/override)
It has the advantage of failing if the method is not virtual in the parent.
edit
As Mark pointed out, it also fails if the signature doesn't match, whereas virtual would silently "succeed". The scare quotes are because a mismatched signature would hide the shadowed method in the base and make a new virtual method that's unrelated.
Upvotes: 7