Why does the following not work when chaining constructors:
#include <iostream>
#include <vector>
class cls {
public:
cls() {cls(5);} // want to resize v to 5
cls(int n) {v.resize(n);}
std::vector<int> v;
};
int main(int argc, const char* argv[]) {
cls x, y(5);
std::cout << x.v.size() << std::endl; // prints 0 <- expected 5
std::cout << y.v.size(); // prints 5
return 0;
}
Demo: http://ideone.com/30UBzS
I expected both objects to have a v
of size 5. What's wrong?
Reason I want to do this is because writing separate cls()
and cls(n)
ctors would duplicate a lot of code.