Variables after the colon in a constructor

numerical25 picture numerical25 · Feb 28, 2010 · Viewed 11.5k times · Source

I am still learning C++ and trying to understand it. I was looking through some code and saw:

point3(float X, float Y, float Z) :
x(X), y(Y), z(Z)  // <----- what is this used for
{
}

What is the meaning of the "x(X), y(Y), z(Z)" sitting beside the constructor's parameters?

Answer

John Knoeller picture John Knoeller · Feb 28, 2010

It's a way of invoking the constructors of members of the point3 class. if x,y, and z are floats, then this is just a more efficient way of writing this

point3( float X, float Y, float Z):
{
   x = X;
   y = Y;
   z = Z;
}

But if x, y & z are classes, then this is the only way to pass parameters into their constructors