Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a private vector

I have a class with a private attribute that is a vector. What is the best way of doing a getter function?

  1. Return the whole vector: vector<char*> getNames() { return names; }
    • Would this return a copy or a pointer? Would this be accessible since its private?
  2. Return the iterator: vector<char*>::iterator getNames() { return names.begin(); }
  3. Make the vector public
    • I know this is bad practice for OOP, just listing options.
like image 914
Sorescale Avatar asked Jan 09 '23 10:01

Sorescale


2 Answers

Return by const vector<char*>&. It makes sure it won't be modified outside and it doesn't make a copy.

like image 175
Sopel Avatar answered Jan 15 '23 14:01

Sopel


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.

like image 41
T.C. Avatar answered Jan 15 '23 15:01

T.C.