VC++ 2013 support for delegating constructors

This is something C# has had for ages, so it is great to finally get it in C++ too. The compiler feature allows a type’s constructor (the delegating constructor) to have another constructor of the type in its initialization list. So when you previously had to write code like this.

class Error
{
public:
  Error()
  {
    Init(0, "Success");
  }

  Error(const char* message)
  {
    Init(-1, message);
  }

  Error(int errorCode, const char* message)
  {
    Init(errorCode, message);
  }

private:
  void Init(int errorCode, const char* message)
  {
    //...
  }
};

With delegating constructors, you can now write it as following.

class Error
{
public:
  Error() : Error(0, "Success")
  {
  }

  Error(const char* message) : Error(-1, message)
  {
  }

  Error(int errorCode, const char* message)
  {
    // ...
  }
};

Bonus reading – Here’s a humorous article written 10 years ago (May 2003) by Herb Sutter and Jim Hyslop on delegating constructors, way before the standards body started considering it as a serious proposal.

Advertisements

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