I have a vector as member in a class and I want to return a reference to it through a getVector() function, so as to be able to modify it later. Isn’t it better practice the function getVector() to be const? However I got an error “qualifiers dropped in binding reference of type…” in the following code. What should be modified?
class VectorHolder
{
public:
VectorHolder(const std::vector<int>&);
std::vector<int>& getVector() const;
private:
std::vector<int> myVector;
};
std::vector<int> &VectorHolder::getVector() const
{
return myVector;
}
Since it is a
constmember function, the return type cannot be non-const reference. Make itconst:Now it is okay.
Why is it fine? Because in a
constmember function, the every member becomes const in such a way that it cannot be modified, which meansmyVectoris aconstvector in the function, that is why you have to make the return typeconstas well, if it returns the reference.Now you cannot modify the same object. See what you can do and what cannot:
By the way, I’m wondering why you need such
VectorHolderin the first place.