Return reference to a vector member variable

Since it is a const member function, the return type cannot be non-const reference. Make it const:

const std::vector<int> &VectorHolder::getVector() const
{
   return myVector;
}

Now it is okay.

Why is it fine? Because in a const member function, the every member becomes const in such a way that it cannot be modified, which means myVector is a const vector in the function, that is why you have to make the return type const as well, if it returns the reference.

Now you cannot modify the same object. See what you can do and what cannot:

 std::vector<int> & a = x.getVector();       //error - at compile time!

 const std::vector<int> & a = x.getVector(); //ok
 a.push_back(10);                            //error - at compile time!

 std::vector<int>  a = x.getVector();        //ok
 a.push_back(10);                            //ok

By the way, I’m wondering why you need such VectorHolder in the first place.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)