Should I use virtual, override, or both keywords?
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.
However, an override
can help avoid bugs by producing a compilation error when the intended override isn't technically an override. For instance, the function type isn't exactly like the base class function. Or that a maintenance of the base class changes that function's type, e.g. adding a defaulted argument.
In the same way, a virtual
keyword in the derived class can make such a bug more subtle by ensuring that the function is still virtual in the further derived classes.
So the general advice is,
Use
virtual
for the base class function declaration.
This is technically necessary.Use
override
(only) for a derived class' override.
This helps maintenance.
Example:
struct Base { virtual void foo() {} };
struct Derived: Base { void foo() override {} };
Notes:
¹ C++ supports covariant raw pointer and raw reference results. With covariance the type of the override isn't exactly the same. It just has a compatible type.
Are there any subtleties in using both the virtual and override keywords in C++11?
Late to the game, but this C++ Core Guideline seems relevant here:
C.128: Virtual functions should specify exactly one of
virtual
,override
, orfinal
Reason
Readability. Detection of mistakes. Writing explicit
virtual
,override
, orfinal
is self-documenting and enables the compiler to catch mismatch of types and/or names between base and derived classes. However, writing more than one of these three is both redundant and a potential source of errors.It's simple and clear:
virtual
means exactly and only "this is a new virtual function."override
means exactly and only "this is a non-final overrider."final
means exactly and only "this is a final overrider."
c++ virtual keyword vs overriding function
Consider the following example. The important line to illustrate the need for virtual
and override
is c->printMe();
. Note that the type of c
is Base*
, however due to polymorphism it is correctly able to call the overridden method from the derived class. The override
keyword allows the compiler to enforce that a derived class method matches the signature of a base class's method that is marked virtual
. If the override
keyword is added to a derived class function, that function does not also need the virtual
keyword in the derived class as the virtual is implied.
#include <iostream>
class Base{
public:
virtual void printMe(){
std::cout << "I am the base" << std::endl;
}
};
class Derived: public Base{
public:
void printMe() override {
std::cout << "I am the derived" << std::endl;
}
};
int main() {
Base a;
Derived b;
a.printMe();
b.printMe();
Base* c = &b;
c->printMe();
return 0;
}
The output is
I am the base
I am the derived
I am the derived
Should I always use the override contextual keyword?
The override
keyword is totally useful and I would recommend using it all the time.
If you misspell your virtual function it will compile fine but at runtime the program will call the wrong function. It will call the base class function rather than your override.
It can be a really difficult bug to find:
#include <iostream>
class Base
{
public:
virtual ~Base() {}
virtual int func()
{
// do stuff for bases
return 3;
}
};
class Derived
: public Base
{
public:
virtual int finc() // WHOOPS MISSPELLED, override would prevent this
{
// do stuff for deriveds
return 8;
}
};
int main()
{
Base* base = new Derived;
std::cout << base->func() << std::endl;
delete base;
}
C++ virtual keyword for functions in derived classes. Is it necessary?
They are exactly the same. There is no difference between them other than that the first approach requires more typing and is potentially clearer.
C++ override specifier without virtual? Does override imply virtual?
The answer you're looking for is in https://en.cppreference.com/w/cpp/language/virtual
If some member function vf is declared as virtual in a class Base, and some class Derived, which is derived, directly or indirectly, from Base, has a declaration for member function with the same
name
parameter type list (but not the return type)
cv-qualifiers
ref-qualifiers
Then this function in the class Derived is also virtual (whether or not the keyword virtual is used in its declaration) and overrides Base::vf (whether or not the word override is used in its declaration).
Is it good or bad style declaring an overridden method with 'virtual' and 'override' keywords?
But is it good style to still add the 'virtual' keyword to the derived method?
In your case, virtual
keyword is implicit in derived class methods as it is propagated down implicitly from class A
to class B
.
Compilers may complain through warning if 'virtual' keyword is not mentioned explicitly.
Pros: Gives clear indication of being virtual
, especially useful in deep class hierarchies.
Cons: Not cleaner or clearer look.
C# - Keyword usage virtual+override vs. new
The "new" keyword doesn't override, it signifies a new method that has nothing to do with the base class method.
public class Foo
{
public bool DoSomething() { return false; }
}
public class Bar : Foo
{
public new bool DoSomething() { return true; }
}
public class Test
{
public static void Main ()
{
Foo test = new Bar ();
Console.WriteLine (test.DoSomething ());
}
}
This prints false, if you used override it would have printed true.
(Base code taken from Joseph Daigle)
So, if you are doing real polymorphism you SHOULD ALWAYS OVERRIDE. The only place where you need to use "new" is when the method is not related in any way to the base class version.
Related Topics
How to Navigate Through a Vector Using Iterators? (C++)
Should I Pass an Std::Function by Const-Reference
How to Give Priority to Privileged Thread in Mutex Locking
Console Output in a Qt Gui App
Find All Substring's Occurrences and Locations
Preincrement Faster Than Postincrement in C++ - True? If Yes, Why Is It
Efficient Bitwise Operations for Counting Bits or Find the Right|Left Most Ones
Why Doesn't Left Bit Shift << Shift Beyond 31 for Long Int Datatype
Why Is the Empty Base Class Optimization (Ebo) Is Not Working in Msvc
Most Optimized Way of Concatenation in Strings
Differencebetween Set and Unordered_Set in C++
How to Construct a Std::String from a Std::Vector<Char>
Which Std::Async Implementations Use Thread Pools
Passing Rvalues Through Std::Bind