Why does following does not work ??

#include<iostream>
using namespace std;

class point{
	float x,y,z;
public:
	point(float f_x =1.0, float f_y=1.0, float f_z=1.0);
	void getxyz(float &x, float &y, float &z);
	

};
point::point(float f_x, float f_y, float f_z)
{
	x= f_x;
	y= f_y;
	z= f_z;
}

void point::getxyz(float &x, float &y, float &z)
{
	x=x+2;
	y=y+2;
	z=z+2;
}
int main()
{
	float X,Y,Z;
	point mylocation(8,3,4);
	mylocation.getxyz(X,Y,Z);
	cout<< X << " " << Y << " " << Z << endl;
	return 0;
}

Output should be 10, 5 ,6

But this program works fine.......

#include<iostream>
using namespace std;

class point{
	float x,y,z;
public:
	point(float f_x =1.0, float f_y=1.0, float f_z=1.0);
	void getxyz(float &x, float &y, float &z);
	float getX();
	float getY();
	float getZ();


};
point::point(float f_x, float f_y, float f_z)
{
	x= f_x;
	y= f_y;
	z= f_z;
}
float point::getX()
{
	return x;
}
float point::getY()
{
	return y;
}
float point::getZ()
{
	return z;
}
void point::getxyz(float &x, float &y, float &z)
{
	x=getX()+2;
	y=getY()+2;
	z=getZ()+2;
}
int main()
{
	float X,Y,Z;
	point mylocation(8,3,4);
	mylocation.getxyz(X,Y,Z);
	cout<< X << " " << Y << " " << Z << endl;
	return 0;
}

Why is so?? (In previous program) After all x can be accessed by the members of same class and getxyz function belongs to same class.

In the malfunctioning sample, you have parameter names for the get function the same as the class's members. In the function, the parameters are in local scope, so the x=x+2; is only referencing the parameter passed in. Thus, you are adding 2 to the uninitialized value of main's X.

How is the compiler to know that you mean two different things, both named 'x' in that function, and in which order they should be used?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.