This syntax means initializing bases and members of a class. Let consider a simple example
1 2 3 4 5 6 7
|
class A
{
public:
A() {}
private:
int x;
};
| |
If we want to add to the class a constructor that will initialize its member x we could write
1 2 3 4 5 6 7 8
|
class A
{
public:
A() {}
A( int i ) { x = i; }
private:
int x;
};
| |
Here inside the body of the consttructor i is assigned to data member x. However the same constructor could be rewritten the following way
1 2 3 4 5 6 7 8
|
class A
{
public:
A() {}
A( int i ) : x ( i ) { }
private:
int x;
};
| |
In fact for fundamental types there is no difference between the two forms of the constructor. However if a user-defined type is used instead of a fundamental type there a big difference.
Consider another class that has ias ts data member the class A
1 2 3 4 5 6 7
|
class B
{
public:
B() {}
private:
A a;
};
| |
We could wtite the constructtor of class B the following way
1 2 3 4 5 6 7
|
class B
{
public:
B( int i ) { a = i; }
private:
A a;
};
| |
What will occur? First of all object a will be created by using the default consttructor A(). Then inside the body of constructor B that to provide the assignment a = i will be called the constructor with parameter A( i ), and after that the temporary object created by A() will be assigned to a. That is there were two constructor and one copy assignment operator called.
If to rewrite constructor B the following way
1 2 3 4 5 6 7
|
class B
{
public:
B( int i ) : a( i ) {}
private:
A a;
};
| |
then only one constructor of class A will be called namely A( int i ).
The reason that before the control will be passed inside the body of a constructor all class data members will be already created by using their default constructors and inside the body copy assignment operators will be called to assign to created members new values. If you use the synrax with ctor initializer you can specify exactly those constructors as you want that they be called and you need not to use copy assignment operators inside the body of the constructor to assign required values to data members. The constructors explicitly specified in the ctor initializer will do all work.