Search code examples
c++vectorsizefieldpush-back

C++ -- Adding elements to private member field std::vector


class T {
private:
  std::vector<T> myVec;
  // ...
public:
  T();
  T(float x, float y);
  std::vector<T> getMyVec() { return myVec; }
  // ...
};

// in T.cpp I don't use myVec in any way (not in the constructor either)

// in Tmain.cpp:

int main() {
  T myT;
  std::cout << myT.getMyVec().size() << std::endl; // 0
  T anotherT(1.1, 2.2);
  myT.getMyVec().push_back(anotherT);
  std::cout << myT.getMyVec().size() << std::endl; // 0
}

Hopefully I can make myself clear (just assume that my #include's etc. are correct):

So basically, I have a class T in which I have a private member field named myVec which is of type std::vector. I also have a public (get-)function to access that field. In main I create myself a T object, and print out its myVec.size(). It's zero as I haven't done anything to the vector yet. I create anotherT object and push_back() it to my vector field of the previous T object. Again I print out the myVec.size() of the former object (I expect it to be 1 at this point, as I've added anotherT to it. But it still returns 0 as its size. Why is that? And how can I make it so that it "saves" the objects I try to add to it?


Solution

  • std::vector<T> getMyVec() { return myVec; }
    

    should be

    std::vector<T>& getMyVec() { return myVec; }
    

    else you return a copy of your member.