RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


C++09 Attributes: Specify Your Constructs' Unusual Properties

Learn how to use attributes, a new C++09 feature, to specify additional information about your programming constructs conveniently and portably.


++ constructs such as functions, types, variables, and blocks are associated with implicit properties that you sometimes need to override. Certain constructs require you to specify their unusual properties, for example:

  • A function that never returns
  • A type with a particular alignment restriction
  • A virtual function that must not be overridden

Attributes, a new C++09 feature, are compile-time tokens that enable you to designate properties like these. By using attributes, you can specify additional information about your programming constructs conveniently and portably. This 10-Minute Solution shows how to apply this technique.

You need to tell the compiler and your fellow programmers how to use a certain component, but you don't want to use nonstandard features or risk inadvertent usage violations.

Use C++09 attributes.

final, Finally

Before the advent of C++09, ensuring that clients could not override a certain virtual function any further was a struggle. Consider the following example:

struct B 
 virtual void f (); //do not override this!
struct D : B {
 void f(); //overriding B::f, uncaught by the compiler

The author of class B made her intentions clear: Any class derived from B must not override f(). Still, an innocent user who derived D from Bmistakenly violated this requirement. A standard C++ compiler cannot detect this violation because all public virtual functions can be overridden by default.

C++09 attributes tackle this problem. An attribute is a token enclosed between double square brackets, for example [[myattribute]]. C++09 defines several attribute tokens, which you need to understand aren't reserved keywords. To indicate that a virtual function must not be overridden any further, you need to appertain the attribute [[final]]to the last permitted override of that function:

struct B //C++09 only 
 virtual void f [[final]] ();//can't override f() any further!

struct D : B {
 void f(); // compilation error: attempt to override B::f

The [[final]] attribute applies to class definitions and to virtual member functions declared in a class definition. If the [[final]] attribute is specified for a class definition, it's equivalent to being specified for each virtual member function of that class, including inherited member functions. The following declaration of class A...

struct A [[final]] //C++09 only
 virtual void f();
 virtual void g();
 virtual void h();

...is equivalent to:

struct A  //C++09 only
 virtual void f [[final]] ();
 virtual void g [[final]] ();
 virtual void h [[final]] ();

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date