Tuesday Apr 24, 2012

C++11 Tidbits: Explicit overrides and final

GCC 4.7.0 was released on March, 22, and among many other new C++11 features (http://gcc.gnu.org/gcc-4.7/cxx0x_status.html), it is now also possible to use the identifiers (1) 'final' and 'override' in a special way. For instance (see override*.C in the C++ testsuite for many other examples):

  struct B1 final { };

  struct D1 : B1 { };              // "cannot derive from 'final' base"

The code is rejected, because D1 tries to derive from B1, which is decorated as 'final'. Likewise, for virtual functions:

  struct B2
  {
    virtual void f() final {}      // "overriding final function"
  };

  struct D2 : B2
  {
    virtual void f() {}
  };

This is rejected too, because D2::f tries to override B2::f, which is decorated with 'final'. Also this is rejected:

  struct B3
  {
    virtual void g(int) {}
  };

  struct D3 : B3
  {
    virtual void g(double) override {}    // "does not override"
  };

This shows that thanks to the 'override' identifier, another whole class of programming errors can be easily avoided. These errors occurred where, due to a wrong signature, a new virtual function was inadvertently declared instead of overriding an existing.

Note however, that all of this isn't just syntactic sugar, useful to avoid many common programming errors. A call to a virtual function marked 'final', like B2::f above, is devirtualized by the GNU C++ front-end thus leading to much more efficient code. Likewise this occurs for any virtual function declared in a class decorated with 'final' as whole, for example B1 above.

(1) Technically those are existing identifiers which acquire a special meaning in some situations in C++11.

About

C++ enthusiasts only, please! ;)

Search

Categories
Archives
« April 2012 »
SunMonTueWedThuFriSat
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
25
26
27
28
29
30
     
       
Today