Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I specify 'virtual' again when I override a C++ function?

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; }
}
like image 510
Derf Skren Avatar asked Jun 13 '14 04:06

Derf Skren


People also ask

Should overridden functions be virtual?

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.

Can a method be both virtual and override?

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.

Can we override a method without virtual keyword?

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.

Is there any reason to mark a function virtual If you are not going to have a derived class?

No, the virtual keyword on derived classes' virtual function overrides is not required.


2 Answers

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.

like image 172
Tony Delroy Avatar answered Oct 10 '22 05:10

Tony Delroy


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.

like image 20
Steven Sudit Avatar answered Oct 10 '22 05:10

Steven Sudit