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) {}
}