Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables after the colon in a constructor [duplicate]

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?

like image 504
numerical25 Avatar asked Feb 28 '10 03:02

numerical25


People also ask

What does colon after constructor mean?

It means that len is not set using the default constructor.

What Does a colon do in CPP?

Two colons (::) are used in C++ as a scope resolution operator. This operator gives you more freedom in naming your variables by letting you distinguish between variables with the same name.

What are constructors in C++?

A constructor is a special type of member function that is called automatically when an object is created. In C++, a constructor has the same name as that of the class and it does not have a return type. For example, class Wall { public: // create a constructor Wall() { // code } };

What is single colon C++?

The single colon could also signify class inheritance, if the class declaration is followed by : and a class name, it means the class derives from the class behind the single colon. 1.


2 Answers

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

like image 98
John Knoeller Avatar answered Sep 20 '22 05:09

John Knoeller


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.)

like image 36
vladr Avatar answered Sep 21 '22 05:09

vladr