Is it dangerous to use both virtual
and override
on a function in C++? Does that open you up for ambiguity with overloading?
Obviously virtual
must be used in the base class and it would be silly to not use override
in the derived class, but is it actually problematic to use virtual
with override
in the derived class?
Trying to determine if this is an issue of style or correctness.
Example:
class Widget { virtual void transmogrify() = 0; } class Gadget : public Widget { virtual void transmogrify() override {} }
The virtual keyword can be used when declaring overriding functions in a derived class, but it is unnecessary; overrides of virtual functions are always virtual. Virtual functions in a base class must be defined unless they are declared using the pure-specifier.
The virtual keyword is used to modify a method, property, indexer, or event declared in the base class and allow it to be overridden in the derived class. The override keyword is used to extend or modify a virtual/abstract method, property, indexer, or event of base class into a derived class.
final Functions and Classes The C++11 keyword final has two purposes. It prevents inheriting from classes, and it disables the overriding of a virtual function.
It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used. A class may have virtual destructor but it cannot have a virtual constructor.
The virtual
keyword has no effect when you are overriding. A derived function that is a signature match for a virtual function defined in a base class will override the base definition, and the override will be entered in the vtable, whether the virtual
keyword is used in the derived class or not.
Because the override
keyword will cause a compile error if overriding is not happening, the virtual
keyword is useless in combination.
Here, have a cheatsheet:
| Keyword used | Matching virtual function in base class | Result | |--------------|-----------------------------------------|--------------------------| | Neither | No | New non-virtual function | | Neither | Yes | Override | | virtual | No | New virtual function | | virtual | Yes | Override | | override | No | Compile error | | override | Yes | Override | | Both | No | Compile error | | Both | Yes | Override |
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