Search code examples
c++functionreferencereturn-valueassignment-operator

Returning a reference to a variable: Meaningful/useful?


Say you have the following code:

MyObject someObject;

MyObject& getReferenceToObject() {
    return someObject;
}

Now consider the following to ways to call getReferenceToObject():

void MyFunction() {
    MyObject obj = getReferenceToObject(); // 1.
    MyObject& obj = getReferenceToObject(); // 2.
}

The compiler allows both 1. and 2. My question is, if I do it like 1., will the Object be copied into the obj variable, or will obj point to someObject? And does 2. make any sense at all?


Solution

  • Version 1. Initialises a MyObject, called obj with the MyObject::MyObject(const MyObject & other); constructor (or similar). obj is a copy of someObject

    Version 2. Initialises a reference to MyObject, (also) called obj, so that it names the same object as someObject.

    If you mutate obj, version 1 will not change someObject, version 2 will.