Member function argument naming problem

Started by
2 comments, last by ROSS128 23 years, 8 months ago
Hi All. Relative C++ newbie here with a strange question, well, at least strange to me. I''m trying to determine what would happen if I had a member function definition who''s arguments had the same names as a member variable in the same class. How would the function know which one you are wanting to use or can it even tell? Here is an example. Note: I am NOT trying to use the arguments of the member function to change the member variable, they just happen to have the same name. class CSomeClass { int x; int y; void fn(int x, int y); }; // Here I am passing arguments with the same names as member // variables CSomeClass::fn(int x, int y) { x += 10; y += 10; } void main() { CSomeClass *someObject; someObject = new CSomeClass; int x_pos, y_pos; x_pos = 10; y_pos = 10; someObject->x = 5; someObject->y = 5; someObject->fn(x_pos, y_pos); } If the member variables get used, then x and y = 15. If the arguments get used then x and y = 20. Am I totally off here? Which x and y get used, the class members or the passed arguments? Or will the compiler just get confused like me? Thanks for any help. Phillip
Advertisement
With a few printfs and a few minutes, you''ll be able to figure it out for yourself.

The Gent
The parameter will override the member variables. If you need to get at your x member variable you can use this->x.

I hope I don''t have to tell you that this is a really really bad thing to do if you have any choice at all. It will cause lots of confusion.

-Mike
Thanks guys. I had a feeling what I was doing could lead to bad things. My initial solution was to just rename the function arguments which made more sense anyway.

Phillip

This topic is closed to new replies.

Advertisement