This is called an initialization list, and is used for initializing class members. It is useful both as a shorthand and it is required for initializing members that do not have a default constructor. For example:
#include <iostream>
using namespace std;
class Foo {
public:
Foo(int x) { cout << "Foo(" << x << ")" << endl; }
};
class Bar : public Foo {
Foo member;
public:
Bar() { /* error */ }
};
This gives an error because member
cannot be default constructed, as Foo
does not have a default constructor. Change it to
Bar(): member(42) {}
and now it works.
This syntax is also useful for initializing const
members of a class, as while they might be default-constructible, you cannot overwrite them in the constructor body.
class Baz {
const member;
public:
Baz(int x): member(x) {}
};
The same idea also applies to references, as they also must be initialized directly. Finally, it is used for specifying arguments for the base class constructor.
class Xyzzy : public Foo {
public:
Xyzzy(int y): Foo(y+3) {}
};