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; }
}
When you override a function you don't technically need to write either virtual or override . The original base class declaration needs the keyword virtual to mark it as virtual. In the derived class the function is virtual by way of having the ¹same type as the base class function.
Two important rules: By default, methods are non-virtual, and they cannot be overridden. Virtual modifiers cannot be used with static, abstract, private, and override modifiers.
You cannot override a non-virtual or static method. The overridden base method must be virtual , abstract , or override . An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.
No, the virtual keyword on derived classes' virtual function overrides is not required.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With