31

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?

n0p
  • 3,399
  • 2
  • 29
  • 50
numerical25
  • 10,524
  • 36
  • 130
  • 209
  • 1
    Duplicate of http://stackoverflow.com/questions/1272680/c-constructor-syntax-question-noob. See also http://stackoverflow.com/questions/1632484/c-initialization-question – outis May 07 '10 at 01:42

3 Answers3

34

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

John Knoeller
  • 33,512
  • 4
  • 61
  • 92
  • 2
    To clarify: If the members are non-PoD types, the members won't be default-constructed and a copy-constructor won't need to be invoked on those members if you use an initialization list. Therefore, it's more efficient. – greyfade Feb 28 '10 at 03:50
  • 6
    **`PoD` = "plain old data" – isomorphismes Jun 15 '15 at 17:38
5

In your example point3 is the constructor of the class with the same name (point3), and the stuff to the right of the colon : before the opening bracket { is the initialization list, which in turn constructs (i.e. initializes) point3's member variables (and can also be used to pass arguments to constructors in the base class[es], if any.)

vladr
  • 65,483
  • 18
  • 129
  • 130
0

Member initialization as others have pointed out. But it is more important to know the following:

When the arguments are of the type float or other built-in types, there's no clear advantages except that using member initialization rather than assignment (in the body of the constructor) is more idiomatic in C++.

The clear advantage is if the arguments are of user-defined classes, this member initialization would result in calls to copy constructors as opposed to default constructors if done using assignments (in the constructor's body).

Kevin Le - Khnle
  • 10,579
  • 11
  • 54
  • 80