Sorescale
Sorescale

Reputation: 41

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.

Upvotes: 4

Views: 1994

Answers (2)

T.C.
T.C.

Reputation: 137414

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.

Upvotes: 2

Sopel
Sopel

Reputation: 1219

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

Upvotes: 7

Related Questions