[C++] returning a reference to member variable - not getting result I would expect?
Here is some code I wrote: http://pastebin.com/1XAC27Ms I have some comments in the code that explain my confusion, but I also summarize here:
in "MyClass" I have a function that returns const Point&, and so it returns the member variable Point that it has.
Why don't I have to declare the Point p const since the get function returns a const reference?
Even though I change a value of the Point p, when I use get again, the value is unchanged. I'm assuming the point is getting copied, but it should be a reference!
How can I return an actual const reference? This seems to be useful for getters so I don't have to copy classes when returning such as cout << instance.getString()
~Thanks
Posted Apr 1, 2016, 5:37 AM UTC
You return a reference. But then you create a local copy. For a reference you need to do it like this:
Note that you cannot call the set-method on the const reference.
Oh that makes total sense! For some reason I thought it magically made Point p a reference since the compiler did not argue (extremely dumb for me to assume). Thank you so much!