Using override with virtual in C++ 11

suggest change

The specifier override has a special meaning in C++11 onwards, if it is appended at the end of a function signature. This signifies that a function is

There is no runtime effect. It is mainly an indication to the compiler.

The example below will demonstrate the change in behavior with or without using override.

Without override:

#include <iostream>

struct X {
    virtual void f() { std::cout << "X::f()\n"; }
};

struct Y : X {
	// Y::f(int) does not override X::f() because the signatures differ.
	// The compiler accepts it. Y::f(int) is a separate function;
	// a call through X& still calls X::f().
	virtual void f(int a) { std::cout << a << "\n"; }
};

With override:

#include <iostream>

struct X {
    virtual void f() { std::cout << "X::f()\n"; }
};

struct Y : X {
	// The compiler will alert you to the fact that Y::f(int) does not 
	// actually override anything. 
	virtual void f(int a) override { std::cout << a << "\n"; }
};

Note that override is not a keyword, but a special identifier which may appear only in function signatures. In all other contexts override still may be used as an identifier:

void foo() {
	int override = 1; // OK. 
	int virtual = 2; // Compilation error: keywords can’t be used as identifiers.
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents