Constructors "initialize" an object. You're already familiar with using statements in the constructor body:
MyClass::MyClass(const MyClass& other) {
x = other.x;
c = other.c;
s = other.s;
}
But before your constructor's body runs, all the members of the object must be initialized, meaning that their constructors run so that you can call their member functions (such as operator=
as in the above example). C++ gives you the opportunity to call the constructors explicitly, with the syntax you gave, in the so-called member initializer list. (They will be called automatically by the compiler if you omit them.) Note that I prefer the following formatting:
MyClass::MyClass(const MyClass& other)
: x( other.x )
, c( other.c )
, s( other.s )
{}
What is happening is that the x
(and c
and s
) constructors are called using the values in parentheses. This is faster, because you're only doing one initialization, not two. This might just seem like a nice convenience, but it is in fact necessary if you have const
members.
Hope that helps!