tagelicht
tagelicht

Reputation: 477

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?

Upvotes: 1

Views: 67

Answers (2)

kadina
kadina

Reputation: 5382

That depends on scope of someObject. First one will just copy the whole object. But if you are planning to use it in second way, someObject should be either global object or static object. Because once you return from getReferenceToObject(), the stack is gone and you can't access local object defined inside the function. So returning local object as reference won't work.

Upvotes: 1

Caleth
Caleth

Reputation: 63019

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.

Upvotes: 4

Related Questions