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 fun
The function getVector
can be declared as const
. It returns a reference that can be modified, so while the actual function doesn't modify anything in the class, the caller will be able to modify internal data.
Declare it as:
std::vector& getVector();
If you want a function to return a vector that can't be modified, the use the const
modifier on both the vector and the function:
const std::vector& getVector() const;