I figured out that it’s possible to initialize the member variables with a constructor argument of the same name as show in the example below.
#include <cstdio>
#include <vector>
class Blah {
std::vector<int> vec;
public:
Blah(std::vector<int> vec): vec(vec)
{}
void printVec() {
for(unsigned int i=0; i<vec.size(); i++)
printf("%i ", vec.at(i));
printf("\n");
}
};
int main() {
std::vector<int> myVector(3);
myVector.at(0) = 1;
myVector.at(1) = 2;
myVector.at(2) = 3;
Blah blah(myVector);
blah.printVec();
return 0;
}
g++ 4.4 with the arguments -Wall -Wextra -pedantic gives no warning and works correctly. It also works with clang++. 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.
Since you asked for the reference in the Standard, here it is, with an example.
§12.6.2/7
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:
It avoids unneccessary copy of the original vector object.