Reputation: 397
Uses of vector using namespace is wrong. Might be a typo. Please change as follows. Use std::vector I have to following code:
class MyClass{
private:
std::vector<float>& myvector;
public:
MyClass(int k,std::vector<float>& vector){
(...)
this->myvector=vector;
(...)
}
I create a MyClass object like this:
(...)
std::vector<float> vector;
vector.reserve(k);
(...)
MyClass A= MyClass(k,vector);
(...)
An error pops out telling me MyVector is an uninitialized reference. I just want MyClass to store some data in MyVector and return it. Should I use pointers instead?.
Thanks
Upvotes: 1
Views: 1664
Reputation: 75688
You need to use the constructor initializer list:
MyClass(int k, std::vector<float>& v)
: myvector(v)
{
(...)
}
Also don't use the name of a type as the name of a variable/parameter.
This great explanation from user3159253
members of the class are initialized before constructor body. So if you don't initialize them explicitly, they're initialized with their respective default constructors. This is often Ok for most datatypes (although they would be initialized twice, once with default constructor and the second time in the body), but not with references which don't have default constructors at all
Upvotes: 4