Identical Class Member Names and Function Argument Names in C++

arguments, c++, members, naming

Solution

Yes, that's fine, and perfectly standard.

Local variables always come first in a name lookup, but the `x(...)` in an initialization list can obviously only refer to member variables [edit:or a base class].

If you didn't use the initialization list, you would have to write:

explicit Foo(T x)
{
    this->x = x;
}

Problem

I have a simple object that holds some [public] data. I want to keep my interface clean, so I don't want to pre-/post- fix anything to the names of the publically accessible variables nor to the names of my function arguments. That said, I ended up doing something like this: ``` template<typename T> struct Foo { explicit Foo(T x) : x(x) // This [i.e., x(x)] seems to be doing the "Right Thing", but is this well defined? {/* ^ No pre-/post- fixing. */ } T x; // No pre-/post- fixing. }; ``` Just to reiterate: All I'm asking is whether this is well defined behavior. Not whether I should or shouldn't be doing this... Thanks.

Original source