'Should I use virtual, override, or both keywords?
In the last weeks something is bugging my brain about virtual and override.
I've learned that when you do inheritance with virtual function you have to add virtual to let the compiler know to search for the right function.
Afterwards I learned also that in c++ 11 there is a new keyword - override. Now I'm a little confused; Do i need to use both virtual and override keywords in my program, or it's better to use only one of them?
To explain myself - code examples of what I mean:
class Base
{
public:
virtual void print() const = 0;
virtual void printthat() const = 0;
virtual void printit() const = 0;
};
class inhert : public Base
{
public:
// only virtual keyword for overriding.
virtual void print() const {}
// only override keyword for overriding.
void printthat() const override {}
// using both virtual and override keywords for overriding.
virtual void printit() const override {}
};
What is the best method?
Solution 1:[1]
According to the C++ Core Guidelines C.128, each virtual function declaration should specify exactly one of virtual, override, or final.
virtual: For the "first" appearance of a function in the base classoverride: For overrides of thatvirtualfunction in a class derived from some base class providing avirtualfunction of the same (or covariant) signaturefinal: For marking an override as unoverrideable. That is, derivatives of a class with afinalvirtual function override cannot have that virtual function override overridden.
struct A {
virtual void go() { puts("A"); }
};
struct B : A {
// Overrides A::go(). No need to specify `virtual` explicitly,
// it already implicitly is virtual and overrideable
void go() override { puts("B"); }
};
struct C : B {
void go() final { puts("C"); }
//virtual void go() override final { puts("C"); } would still compile,
// but it is considered, for lack of a better description, "extra"
};
struct D : C {
// Would produce error C3248 : 'C::go' : function declared as 'final' cannot be overridden by 'D::go'
//void go() override { puts("D"); }
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Edgar Bonet |
