codekiddy
codekiddy

Reputation: 6137

Explicit overrides and final c++0x

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

Upvotes: 5

Views: 5112

Answers (1)

NPE
NPE

Reputation: 500417

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 ]

Upvotes: 16

Related Questions