Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit overrides and final c++0x

Tags:

c++

c++11

According to Wikipedia, in this example:

struct Base {
    virtual void some_func(float);
};

struct Derived : Base {
    virtual void some_func(float) override;
};

I thought override was not a C++ keyword, so what does it really mean? We can achieve the same thing without that keyword so why would anyone need it?

There is also the keyword final which does not yet work on VS2010 :

struct Base1 final { };

struct Derived1 : Base1 { }; // ill-formed because the class Base1 
                             // has been marked final
like image 362
codekiddy Avatar asked Jan 04 '12 16:01

codekiddy


People also ask

What is override final?

We know that override and final is indepent sematically. override means the function is overriding a virtual function in its base class. See f1() and f3() . final means the function cannot be overrided by its derived class.

What is override in C ++ 11?

C++11 adds two inheritance control keywords: override and final. override ensures that an overriding virtual function declared in a derived class has the same signature as that of the base class. final blocks further derivation of a class and further overriding of a virtual function.


1 Answers

In C++11, override and final are "identifiers with special meaning". They are not keywords and only acquire special meaning if used in a specific context (when declaring virtual functions).

The idea is to enable to compiler to catch certain types of errors by allowing the programmer to explicitly state their intent (e.g. to override an existing virtual function rather than create a new one).

Here is the relevant quote from the standard, with examples:

C++11 10.3 4 If a virtual function f in some class B is marked with the virt-specifier final and in a class D derived from B a function D::f overrides B::f, the program is ill-formed. [ Example:

struct B {
virtual void f() const final;
};
struct D : B {
void f() const; // error: D::f attempts to override final B::f
};

—end example ]

5 If a virtual function is marked with the virt-specifier override and does not override a member function of a base class, the program is ill-formed. [ Example:

struct B {
virtual void f(int);
};
struct D : B {
void f(long) override; // error: wrong signature overriding B::f
void f(int) override; // OK
};

—end example ]

like image 179
NPE Avatar answered Sep 21 '22 17:09

NPE