-
constructor
Hi all!
I'm writing a program in which I define a class named Point. the objects of the class are points of 2 numerical coordinates(x and y). I wanna write a constructor for my class with the following signature:
Point(int x,int y)
should I write anything in the body of my constructor or should I leave it empty?
I mean sth like this:
Code:
class Point
{
public:
int x,y;
Point(int x,int y)
{
Point::x=x;
Point::y=y;
}
};
is it ok to do so?
I wanna tell the constructor to set the x and y attributes of the objects as written in the parenthesis that come after them. if I leave it's body empty, does it know to do such a thing?
-
The best way to do this is via an initializer list:
Code:
Point(int x_, int y_) : x(x_), y(y_) {}
note I changed the names of the variables coming in to set them apart from the member variables.
-
If you're using initialization list syntax, the names of the arguments can be the same as the member names, and the compiler is smart enough to know what to do:
Code:
Point(int x, int y) : x(x), y(y) {}
Code:
Point(int x,int y)
{
Point::x=x;
Point::y=y;
}
};
This would work if x and y were static, for non-static members, you could alternatively do this:
Code:
Point(int x,int y)
{
this->x=x;
this->y=y;
}
};
The initialization list is the preferred way to do this in a constructor, but you can use this in any other place you need to differentiate a member variable from a local, for example.
-
Good to know, NeonBlack. I always use trailing underscores on my member variables for differentiation to prevent myself from getting confused anyway :)
-
Thank you all! it helped me a lot. but could you please explain a little bit more why my code works for static members and not non-static ones?