what is mean by x(x)

Dec 15, 2015 at 7:00am
Point(int x = 0,int y =0):x(x),y(y){};
Dec 15, 2015 at 7:04am
Assuming that Point is constructor of Point class; it is initializing members x, y using params passed to the constructor
Dec 15, 2015 at 7:12am
why still need x(x),i dont understand
Dec 15, 2015 at 7:36am
Because you need to initialize it to some value; otherwise when you call the constructor in some other part of your code, you'll get trash values and your program most likely won't do what you want.
Dec 15, 2015 at 7:38am
Constructors are supposed to initialize class data members. It can be achieved by
 
inline Point(int inX=0; int inY=0): x(inX), y(inY) {};


OR

1
2
3
4
5
inline Point(int inX=0; int inY=0)
{
    x = inX;
    y = inY;
};
Dec 15, 2015 at 2:24pm
@codewalker

Your second snippet is a very inefficient version of the first one, and isn't recommended.

If the the type of parameters is not a built in C++ type like int, char, or double say, then the second snippet creates unnamed, unrelated temporary copies of the constructor parameters, after they had already been initialised with the default value, then it initialises them again with the actual values in the constructor body.

The first snippet uses direct initialisation once, before any (if any) default initialisation. So this is the preferred option, it's efficient no matter what the types are.

Dec 15, 2015 at 2:39pm
@OP: that's called initialization list.
You'll also need it to initialize the base class, any constant member, or any member that doesn't have a default constructor.
Dec 15, 2015 at 6:10pm
Just to note, that example code is confusing, because the writer has clearly used the same name, x, for both the data member, and the constructor argument. x(x) in the initialiser list means "initialise the data member x, with the value passed in as the parameter x".

Was that from a textbook?
Dec 15, 2015 at 6:22pm
MikeyBoy wrote:
Just to note, that example code is confusing, because the writer has clearly used the same name, x, for both the data member, and the constructor argument.

I do this all the time.
Dec 17, 2015 at 11:29pm
the parameter of constructor can be same name as the private member function??
Dec 18, 2015 at 12:10am
yes you can but it's not recommended for several reasons.

for someone who is reading the code for example when the definition is too big.
Topic archived. No new replies allowed.