Returning a const reference to vector of an object
c++, constants, reference, return
Solution
Line 3 works because t2 is copy-constructed from the reference returned by getS()
The way you const-qualify the reference returned by getS() is OK. You could const-qualify getS() as well, i.e.:
const vector<int>& getS()const;
so that getS() could be called on a const sys.
Problem
I have 2 questions related to the same problem: How can I return a reference to a vector which belongs to a class? I have this class: ``` class sys{ protected: vector<int> s; public: sys(); vector<int>& getS() {return s;} //(1) }; ``` (1) should return the reference of the vector `s`. However, in `main()`: ``` main(){ sys* my_sys = new sys(); vector<int> &t1 = my_sys->getS(); //(2) vector<int> t2 = my_sys->getS(); //(3) ... } ``` - `t1` is a reference to `s` (i.e. when `t1` is changed `my_sys.s` is changed as well). - `t2` is a COPY of `s` (i.e. when `t2` is changed my_sys.s is NOT changed). Why does line (3) work? I do not want it to be possible to change `my_sys.s` outside of the class, but I want to return a reference because of efficiency. Where do I put the `const`? I tried to change line (1) to ``` const vector<int>& getS() {return s;} //(4) ``` but I am not sure if that is enough.