Reto Höhener
Reto Höhener

Reputation: 5808

I have trouble writing a getter for a vector

Why does item.someVector.push_back(1); seem to work, but not item.getSomeVector().push_back(1); ?

Here is my test case:

#include <iostream>
#include <vector>

using namespace std;

class Item {
public:
  vector<int> someVector = vector<int>();
  vector<int> getSomeVector()
  {
    return someVector;
  }
};

int main()
{
  Item item = Item();

  item.getSomeVector().push_back(1);
  cout << item.getSomeVector().size() << endl;
  cout << item.someVector.size() << endl;

  item.someVector.push_back(1);
  cout << item.getSomeVector().size() << endl;
  cout << item.someVector.size() << endl;
}

// output:
// 0
// 0
// 1
// 1

Upvotes: 1

Views: 519

Answers (1)

Michael Albers
Michael Albers

Reputation: 3779

Because getSomeVector returns a copy of someVector. So you're updating a temporary object which is then immediately destroyed. Try changing it to vector<int>& getSomeVector()

Upvotes: 7

Related Questions