I’m using Qt with C++ and I don’t seem to understand something that feels inconsistent to me.
I have a method that manipulates the variables that are sent to it as parameters, here is its declaration aManipulation(qreal& a); //reference to a qreal
I use QPointF which contains two qreal values. The class can return a qreal value through a method, or a reference qreal& through another method. So I’m curious about these cases:
qreal value = 1;
QPointF point; point.setX(1);
//OK -- this works eventhough I don't send it as a qreal&
aManipulation(value);
//FAIL -- actually trying to send a qreal& reference is an error
aManipulation(value&);
//OK -- this method however returns a qreal&
aManipulation(point.rx());
//FAIL -- this just returns the '1' and I understand it cannot be referenced
aManipulation(point.x());
Why is it enough to send the object and not a reference to the object to a method that wants a reference of an object? I am confused as doing this with pure pointers would be very clear.
When you pass ‘value’ to:
by saying:
the compiler actually passes a reference to myreal, there’s no need to say ‘myreal&’ (in fact, you can’t).
Passing pointers may seem clearer, but the reference approach is safer. You still get the benefit of passing an address to something – instead of the whole something – without the risk of the pointer being modified.
I think the code’s cleaner too. You don’t have all the ‘*’ or the need for putting ‘const’ in the right place to keep the pointer from being modified while still allowing what it points to be.
When I look at my old code with all the pointers being passed around, it looks pretty ugly to me, but that’s subjective. Of course there are times you actually want to pass pointer (or pointers to pointers).