What Is the 'Override' Keyword in C++ Used For

What is the 'override' keyword in C++ used for?

The override keyword serves two purposes:

  1. It shows the reader of the code that "this is a virtual method, that is overriding a virtual method of the base class."
  2. The compiler also knows that it's an override, so it can "check" that you are not altering/adding new methods that you think are overrides.

To explain the latter:

class base
{
public:
virtual int foo(float x) = 0;
};


class derived: public base
{
public:
int foo(float x) override { ... } // OK
};

class derived2: public base
{
public:
int foo(int x) override { ... } // ERROR
};

In derived2 the compiler will issue an error for "changing the type". Without override, at most the compiler would give a warning for "you are hiding virtual method by same name".

Is the 'override' keyword just a check for a overridden virtual method?

That's indeed the idea. The point is that you are explicit about what you mean, so that an otherwise silent error can be diagnosed:

struct Base
{
virtual int foo() const;
};

struct Derived : Base
{
virtual int foo() // whoops!
{
// ...
}
};

The above code compiles, but is not what you may have meant (note the missing const). If you said instead, virtual int foo() override, then you would get a compiler error that your function is not in fact overriding anything.

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.

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;
}

Is there any point in using `override` when overriding a pure virtual function?

However, in the case of a pure virtual function, the compiler would throw an error if we used an incorrect signature in the Derived class

No, this compiles:

class Base {
virtual void my_function() = 0;
};

class Derived : Base {
void my_function(int);
// ^^^ mistake!
};

While this does not:

class Base {
virtual void my_function() = 0;
};

class Derived : Base {
void my_function(int) override;
};

error: void Derived::my_function(int) marked override, but does not override


The error you're talking about only occurs when instantiating Derived - override allows you to catch the mistake earlier and makes the definition of Derived clearer/more readable.

What is the difference between the override and new keywords in C#?

The following page summarizes your question very nicely.

Knowing When to Use Override and New Keywords

Summary

Override: When a method of a base class is overridden in a derived class, the version in the derived class is used, even if the calling code didn't "know" that the object was an instance of the derived class.

New: If you use the new keyword instead of override, the method in the derived class doesn't override the method in the base class, it merely hides it.

If you don't specify either new or overrides, the resulting output is the same as if you specified new, but you'll also get a compiler warning (as you may not be aware that you're hiding a method in the base class method, or indeed you may have wanted to override it, and merely forgot to include the keyword).

Override: used with virtual/abstract/override type of method in base class

New: when base class has not declared method as virtual/abstract/override

Can i override non virtual function in c++

You do not override say in B

from C++ override specifier :

In a member function declaration or definition, override ensures that the function is virtual and is overriding a virtual function from a base class. The program is ill-formed (a compile-time error is generated) if this is not true.

Look at that example :

#include <iostream>

class A
{
public:
void say()
{
std::cout << "From A\n";
}
};

class B : public A {
public:
void say()
//override
{
std::cout << "From B\n";
}
};

int main()
{
A a;
B b;

a.say();
b.say();
((A &) b).say();
}

Compilation and execution :

pi@raspberrypi:/tmp $ g++ c.cc
pi@raspberrypi:/tmp $ ./a.out
From A
From B
From A
pi@raspberrypi:/tmp $

Putting say virtual in A (so implicitely in B) ((A &) b).say(); prints From B because that time there is overriding

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


Related Topics



Leave a reply



Submit