Initializing member variables using the same name for constructor arguments as for the member variables allowed by the C++ standard? [duplicate]

I wonder what the C++ standard says about it? Is it legal and guaranteed to always work?

Yes. That is perfectly legal. Fully Standard conformant.

Blah(std::vector<int> vec): vec(vec){}
                             ^   ^                           
                             |   |
                             |    this is the argument to the constructor
                             this is your member data

Since you asked for the reference in the Standard, here it is, with an example.

ยง12.6.2/7

Names in the expression-list of a mem-initializer are evaluated in the scope of the constructor for which the mem-initializer is specified.

[Example:
class X {
 int a;
 int b;
 int i;
 int j;
 public:
 const int& r;
  X(int i): r(a), b(i), i(i), j(this->i) {}
                      //^^^^ note this (added by Nawaz)
};

initializes X::r to refer to X::a,
initializes X::b with the value of the
constructor parameter i, initializes
X::i with the value of the constructor
parameter i, and initializes X::j with
the value of X::i; this takes place
each time an object of class X is
created. ]

[Note: because the
mem-initializer are evaluated in the
scope of the constructor, the this
pointer can be used in the
expression-list of a mem-initializer
to refer to the object being
initialized. ]

As you can see, there’re other interesting thing to note in the above example, and the commentary from the Standard itself.


BTW, as side note, why don’t you accept the parameter as const reference:

 Blah(const std::vector<int> & vec): vec(vec) {}
      ^^^^const              ^reference

It avoids unneccessary copy of the original vector object.

Leave a Comment