0
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?

Masked Man
  • 1
  • 7
  • 40
  • 80
Beko
  • 982
  • 3
  • 15
  • 26
  • 3
    Hint 1): Your getter returns a copy. Hint 2) if you want to expose the private member so that is tan be written to, you might as well make it public. Hint 3) Maybe you need a method `void add_element(float x);` that adds the element to your private vector. – juanchopanza Dec 28 '14 at 10:55
  • Hint 3): Read about C++ references. You are destroying encapsulation with that though and making the member public is effectively the same. – Ulrich Eckhardt Dec 28 '14 at 10:58
  • You will run into problems if you later decide to use a different container (such as list or queue) instead of a vector. Don't expose your implementation in the interface. Provide a method to add elements to your vector, if the implementation changes in future, only that method needs to change, and not the calling code. – Masked Man Dec 28 '14 at 11:04
  • Thanks to everyone. All answers were quite useful. Have a nice day. – Beko Dec 28 '14 at 11:34
  • @Beko If your question is answered, accept one of the answers. Don't edit the question title. – Masked Man Dec 28 '14 at 11:38
  • @Happy Ah, didn't know that. Done^^ – Beko Dec 28 '14 at 12:16

2 Answers2

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

should be

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

else you return a copy of your member.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
0

You need to return a reference to your private vector.

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

Else it will return a copy. And whatever changes you make to the copy will not affect your vector in the class.

wingerse
  • 3,670
  • 1
  • 29
  • 61