HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
usedoverridetheforwhatkeyword

Problem

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.

Solution

The override keyword serves two purposes:

  • It shows the reader of the code that "this is a virtual method, that is overriding a virtual method of the base class."



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

Context

Stack Overflow Q#18198314, score: 516

Revisions (0)

No revisions yet.