I have a class with a private attribute that is a vector. What is the best way of doing a getter function?
vector<char*> getNames() { return names; }
vector<char*>::iterator getNames() { return names.begin(); }
Return by const vector<char*>&
. It makes sure it won't be modified outside and it doesn't make a copy.
If you are actually using a vector<char *>
internally, the only way to ensure that the user won't modify the names (without an ugly and obvious const_cast
) would be returning a vector<const char *>
by value:
vector<const char *> getNames() const { return {names.begin(), names.end()}; }
or, pre-C++11:
vector<const char *> getNames() const { return vector<const char *>(names.begin(), names.end()); }
Returning a vector<char *>
, either by value or by const reference, would prevent the user from modifying your vector itself, but not the contents of the strings it point to.
It's much better to use a vector<std::string>
, in which case you can simply return a const reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With