Skip to content

Delegating constructors

July 25, 2013

A feature that I had been waiting a long time for is the ability to delegate constructors. To delegate a constructor means that one constructor can call another to initialise the object. When member object initialisation needed to be shared between constructors, or one constructor was the same as another but with some default arguments, the only way to do this was to either duplicate code or call some common function. Both have their problems, the first being that duplicated code is usually bad, the second being that you throw out any initialisation list advantages that you might get by calling some common function in the body of the constructor. Delegating constructors fixes this.

The syntax is quite simple, you simply call the constructor as the only item in an initialiser list. For example, the default constructor delegates to the integer constructor with the argument 42.

class C
{
  public:

  C(int) { }
  C() : C(42) { }
};

The standard specifies that if a constructor delegates to itself, the program is ill-formed. It also states that in that case no diagnostic is required. Given this example right out of the standard

class C
{
  public:

  C(int) { }
  C() : C(42) { }
  C(char) : C(42.0) { }
  C(double) : C('a') { }
};

int main()
{
  C c('b');
  return 0;
}

Clang complains with the following error

delegate.cpp:8:15: error: constructor for 'C' creates a delegation cycle
      [-Wdelegating-ctor-cycles]
  C(double) : C('a') { }
              ^
delegate.cpp:7:3: note: it delegates to
  C(char) : C(42.0) { }
  ^
delegate.cpp:8:3: note: which delegates to
  C(double) : C('a') { }
  ^
1 error generated.

GCC issues no such error, and compiles. The resulting executable crashes with a stack overflow. So be careful when you delegate constructors that you don’t create an infinite loop, because your compiler might not pick it up.

Advertisements

From → Uncategorized

2 Comments
  1. Note that constructor delegation is now supported as per the 2011 specification of ISO C++.

    • Yeah I know, I said I _had_ been waiting for it. I was implying that I was no longer waiting. As far as I can tell, both Clang and GCC have implemented all of the core language.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: