What is the 'override' keyword in C++ used for? [duplicate]
Asked Answered
R

4

319

I am a beginner in C++. I have come across override keyword used in the header file that I am working on. May I know, what is real use of override, perhaps with an example would be easy to understand.

Ronel answered 12/8, 2013 at 23:29 Comment(4)
Note also c++11 introduced the final keyword.Recursion
@JesseGood and again: final also is not a keyword !!!Sicular
@Sicular it's a contextual keywordKarolekarolina
It's something inspired from Java's @Override to let compiler do the compile time checking for youGerda
E
496

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".

Embolden answered 12/8, 2013 at 23:36 Comment(4)
shouldn't the function header for* foo* be similar in class derived2 ?? I compiled this with VS2017 and got a compile error. I mean that inderived2 foo's header must be: *int foo ( float x) override {...} *Loon
Uhm, that's entirely the point, the code example shows how override can be used to detect an error!Embolden
I think #3 is that override can be used to detect the to-be-overridden function (belonging to the parent class/interface) is removed (not alternated). This is useful if the subclass is expecting a callback but it will never happen due to the library change, etc.Josiahjosias
I don't think the compiler can do that without scanning all of the call-graph, and if the compiler does that, it won't need override to understand that. It's really hard to achieve that.Embolden
S
90

And as an addendum to all answers, FYI: override is not a keyword, but a special kind of identifier! It has meaning only in the context of declaring/defining virtual functions, in other contexts it's just an ordinary identifier. For details read 2.11.2 of The Standard.

#include <iostream>

struct base
{
    virtual void foo() = 0;
};

struct derived : base
{
    virtual void foo() override
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }
};

int main()
{
    base* override = new derived();
    override->foo();
    return 0;
}

Output:

zaufi@gentop /work/tests $ g++ -std=c++11 -o override-test override-test.cc
zaufi@gentop /work/tests $ ./override-test
virtual void derived::foo()
Sicular answered 12/8, 2013 at 23:50 Comment(6)
It works (here and for final) because you can't use regular identifiers where these contextual keywords would be placed.Raseda
why the hell it's not forbidden?Bye
@FerencDajka 1. Why should it be? 2. Suddenly adding a new keyword (i.e. forbidding the use of it everywhere else) would break backwards compatibility.Ronnaronnholm
ordinal or ordinary ?Hibben
What is "The Standard"? Google has zillions of things called "Standard"... Link please?Sperrylite
@Sperrylite isocpp.org/std/the-standard The word "standard" refers to something that is officially agreed upon internationally. For example, the definition of how long a meter is is a standardReflate
G
14

override is a C++11 keyword which means that a method is an "override" from a method from a base class. Consider this example:

class Foo
{
public:
    virtual void func1();
};

class Bar : public Foo
{
public:
    void func1() override;
};

If B::func1() signature doesn't equal A::func1() signature a compilation error will be generated because B::func1() does not override A::func1(), it will define a new method called func1() instead.

Garica answered 12/8, 2013 at 23:33 Comment(2)
According to C++ specification, "override" is an "identifier with special meaning". But such things in C# are called contextual keywords.Wrinkly
I think there's someting incorrect in this snippet. For the compiler to issue an error, the signature in Bar, the derived class, would have to be different, as in void func1(int v) override; in order for the compiler to issue an error like `marked 'override', but does not override. IOW: Oddly enough, the override seems a hint for the compiler to use in the derived class, to verify that the same signature exists in the base. See Mats Petersson answer above.Reservoir
V
0

Wikipedia says:

Method overriding, in object oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes.

In detail, when you have an object foo that has a void hello() function:

class foo {
    virtual void hello(); // Code : printf("Hello!");
};

A child of foo, will also have a hello() function:

class bar : foo {
    // no functions in here but yet, you can call
    // bar.hello()
};

However, you may want to print "Hello Bar!" when hello() function is being called from a bar object. You can do this using override

class bar : foo {
    virtual void hello() override; // Code : printf("Hello Bar!");
};
Vivisect answered 12/8, 2013 at 23:42 Comment(2)
You don't need the override identifier to do this in C++, it simply enforces that you are doing it properly.Euterpe
Hi, indeed the wikipedia concept is good as a general basis, but as Goose mentions, the specifics of C++ add a twist: It's used in the derived class to help the compiler identify issues in your code, in this case, that the virtual function exists in the base. The devil is in the details. See Marks Petersson comment above.Reservoir

© 2022 - 2024 — McMap. All rights reserved.