Question

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.

Was it helpful?

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;
}

OTHER TIPS

Specifically for the initializer list of a ctor, it's well-defined behavior -- since you can only initialize a member or base class, there's no ambiguity between one of those and the name of a parameter.

Under almost any other circumstance, however, you'll create an ambiguity. In particular, your title simply refers to "function" -- and for any function other than the ctor, this won't work. Even inside the body of the ctor, it won't work -- the "special" treatment is purely within the initializer list of a ctor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top