[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

13
TheShallowOne•
Point p = c->getPoint();

You return a reference. But then you create a local copy. For a reference you need to do it like this:

const Point& p = c->getPoint();

Note that you cannot call the set-method on the const reference.

1
Mart37OP•

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!

1
Meefims•
Point p = c->getPoint();

This is invoking the copy constructor for a point. If you want p to be a reference then you need to declare it as a reference.

1