I was wondering how using an & to access a certain memory location changed the nature of a function call. For example, if I had written a function to set the radius of a circle
//True, if success, False if radius is off-screen
bool SetRadiusCircle(Circle &b, int r)
This was an example given in the assignment my professor gave me. I just wanted to know how the “&” he included in the sample function call differed from simply using Circle b.
Yes. If you use &, you are passing the circle as a reference. If you don’t use it, you are passing a copy of the circle object, copy that gets created by the compiler for you. This triggers the class copy constructor (either the one you defined, or the default one, which is a bitwise copy).
With a reference, you are not copying the object. You are instead getting the object you had in the caller. It’s equivalent of having an alias to the original object, and any change you perform will apply to the object passed. In the case of a copy, any change to the object is lost at the end of the call, because the copy is destroyed.
When you use a reference, the internal use of that argument requires you to use the
.to access that object’s members (e.g.b.getRadius()). If you defined your function to accept a pointer instead (func (Circle *bPtr)) then you must use the->(e.g.bPtr->getRadius()). Using a pointer is different from using a reference, but the final, practical effect is the same: you get to manipulate the original object, not a copy.Note that this is valid in the function definition. An & used in another context gives you the pointer where something resides. They are not the same, although they use the same symbol.