Sunday, May 27, 2012

C++11 Delegating Constructors.

Another much needed improvement to c++ is the problem of code reuse in constructors. Often you where forced to create an "init" function and call that from the body of the constructor. What this means is that you are effectively default constructing the member variables of the object and then re-initializing them to setup them uin p the common "init" function.

The new standard fixes this by allowing Delegating Constructors. Basically one constructor can now call another one from the same class in its place.

Heres an example:
//compile with  g++ -std=c++11 $< -o $@
#include <iostream>

class DelgateConstructor
  std::string str_;

  DelgateConstructor(char* s) : 
    std::cout << "Working...\n";

  DelgateConstructor() :
    DelgateConstructor("Here we are") 
    std::cout << str_ << "\n";

int main()
  DelgateConstructor whatever;
This results in this output:
Here we are

No comments:

Post a Comment