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?
It means that len is not set using the default constructor.
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.
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 } };
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.
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
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With