-1

I saw this piece of code

class Foo {
public:
  int x;
  double y;
  float z;

  Foo(int x, double y, float z)
  // XXX: What are the following doing?
    : x(x),
      y(y),
      z(z) {}

}

I'm guessing what was written after the : is assigning the values to the members (x, y, z ) from the arguments.

Question 1: Why that way and not the following?

  Foo(int x, double y, float z) {
     this->x = x;
     this->y = y;
     this->z = z;
  }

Question 2: in the original style, how does the compiler distinguish the member x from the parameter x? (In my modified pice of code, the qualifier this was used for that purpose)

For example, if I were to write this:

 Foo(int x, double y, float z)
          // XXX: What are the following doing?
            : x(x * 2),
              y(x * 3 + y ),  // which 'x' is the 'x' in 'x * 2'?              
              z(z) {}

        }
One Two Three
  • 22,327
  • 24
  • 73
  • 114

1 Answers1

0

You guess correctly. Those are member initializer lists. The reason this is preferred over directly assigning in the constructor is because it is necessary for const class members, classes with no default constructors, and reference variables. Example:

class A
{
    int b;
public:
    A(int c) : b(c) {}; // No default constructor
};

class Test
{
    A a;         // A class with no default constructor
    const int x; // A constant
    int& r;      // A reference
public:
    Test(int d) : a(5), x(2), r(d) {};
};

int main()
{
    Test test;
}

In this example, both members a and x of class Test cannot be assigned to because the first has no default constructor, while the latter is constant, meaning assignment to it would create an error. Finally, since reference variables cannot be assigned to, an initializer list is needed.

In the end, the primary difference comes down to the fact that initializer lists initialize the variable (who knew?), while assignment in the constructor is done after those member variables' constructors have been called.

As for your second question, you can see for yourself that the parameters are picked before the member variables during the initialization.

Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88