Archive for Coding

C++11 Delegating Constructors

C++ 11 introduces a new feature called “delegating constructors”. Now you can do common initialization steps in a constructor, known as the target constructor. Other constructors can call the target constructor to do the initialization. These constructors are called delegating constructors.


class A{
public:
A(): A(0) {}
A(int i): A(i, 0) {}
A(int i, int j)
{
...
}
...
};

Delegating constructors cannot have initializations of class members in their initializer lists; that is, a constructor cannot delegate and intialize at the same time.

If an exception occurs in the body of a target constructor, it can be caught by the try block of the delegating constructor.


class A{
public:
A();
A(int i);
A(int i, int j);
};
A::A() try: A(0) {
cout << "A() body"<< endl; } catch(...) { cout << "A() catch"<< endl; } A::A(int i) try : A(i, 0){ cout << "A(int i) body"<< endl; } catch(...) { cout << "A(int i) catch"<< endl; }

This feature helps to reduce the code size and make your program more readable and maintainable.

C++11 range-based for loops

Great link: Range-based for loop

Nowadays, almost every programming language has a convenient way to write a for loop over a range of values. Finally, C++ 11 has the same concept; this is a long awaited C++ feature.

Here’s an example:


vector<string> vec;
vec.push_back( "hello" );
vec.push_back( "world" );

for (string s : vec )
{
cout << s;
}