0

Going through how a copy constructor is created, I came across this example:

class MyClass 
{
      int x;
      char c;
      std::string s;
};

which is copied by the compiler as:

 MyClass::MyClass( const MyClass& other ) : x( other.x ), c( other.c ), s( other.s )
  {}

What is the meaning of : x( other.x )... in the same line as the function header line? How does it work?

Exceptyon
  • 1,584
  • 16
  • 23
James Hallen
  • 4,534
  • 4
  • 23
  • 28
  • only in constructors: initialize the variable x calling the specified constructor x(other.x) that is int(int). You should call the constructors in the same order you declared the variables in your class – Exceptyon Jun 30 '14 at 14:06
  • 3
    The name of the feature is *member initializer list*, it's also called *mem-initializer-list* or sometimes just (confusingly) *initializer list*. Not to be confused with *braced initializer list* or `std::initializer_list`. – dyp Jun 30 '14 at 14:11

1 Answers1

5

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!

George Hilliard
  • 15,402
  • 9
  • 58
  • 96
  • Thanks, for the explanation, regarding your last line, why is it necessary if I have `const` memebers? – James Hallen Jun 30 '14 at 14:23
  • 1
    Good question :). It is necessary because `const` members are defined, roughly, as being unable to be changed after construction. Your only chance to construct them is in the initializer list. – George Hilliard Jun 30 '14 at 14:24