Hi there,
I have 2 questions related to the same problem:
1) How to 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 the 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?
2) I do not want that it is 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.
Thanks for your help.