It is an initialization list. It allows you constructing your member variables directly with the values you want to assign them, rather than default-constructing them and then assigning them in the body of your constructor.
Suppose you have a class A
with a default constructor and a constructor accepting one argument:
struct A
{
A() : n(0) { } // For scalar types, n = 0 in the constructor's body is equivalent
A(int n) : n(a) { } // Should be marked as "explicit", but not relevant here
int a;
};
And a class X
with a member variable of type A
. The constructor of X
takes an argument of type int
which needs to be assigned to A
's variable a
. Without an initialization list, this is how you would do it:
struct X
{
X(int n) { a.a = n; } // First invoke A::A(), then assign n to a.a
A a;
};
But here you have two instructions rather than one: a (potentially expensive) default construction of your member variable a
, followed by an assignment to change its state as desired. If you already know the arguments with which a
should be constructed, it does not make sense to perform a default construction first just to override that initialization.
It must be said, though, that when initializing scalar types (as is the case of your example), the form based on initialization lists is equivalent to the one based on regular assignments in the constructor's body, since scalar types are not zero-initialized by default (more precisely, they are not initialized in any way).
As a related information, in an initialization list the name of your constructor's arguments won't hide the name of the member variables you want to construct:
struct X
{
X(int a) : a(a) { } // OK (although I do not like it)
int a;
};
In a regular assignment, on the contrary, a
would be regarded to be the constructor's argument on both sides of the assignment:
struct X
{
X(int a) { a = a; } // Self-assignment of the constructor's argument...
int a;
};
This said, I do not consider a good practice to use identical names for member variables and function arguments. I mentioned it because it is good to be aware of this if you will have to read code written by others.