Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a reference return value to a non-reference variable

Tags:

c++

reference

class A { ... };
A& getA();
A anA = getA();

What happens exactly on line 3 ?

Is the copy constructor of A called, thus creating an object independent from the one returned (by reference) by the function?

like image 307
Sébastien Avatar asked Jun 10 '15 11:06

Sébastien


People also ask

Can we assign a value to a reference variable?

However, in Python, variable is just a name given to an object in the memory. Even if we assign its value to another variable, both are in fact referring to same object in memory. This can be verified by id() function. It therefore is clear that in Python, we can not create reference to a variable.

How can we return value by reference by using reference variable?

The return type of the function test is string& . This makes it return a reference to the variable str instead of the variable itself. Note how the function call is used on the left side of the assignment statement on line 16. Since the address of str is returned, it can be assigned a value.

Can a reference be the return type for a function?

Functions can be declared to return a reference type. There are two reasons to make such a declaration: The information being returned is a large enough object that returning a reference is more efficient than returning a copy. The type of the function must be an l-value.

How do you create a reference variable of an existing variable?

Reference variable is an alternate name of already existing variable. It cannot be changed to refer another variable and should be initialized at the time of declaration and cannot be NULL. The operator '&' is used to declare reference variable.


1 Answers

Is the copy constructor of A called, thus creating an object independent from the one returned (by reference) by the function?

Yes. The copy constructor takes a reference to the source object as it's parameter and a copy is independent of the original object assuming the copy constructor does a deep copy.

like image 171
eerorika Avatar answered Oct 12 '22 02:10

eerorika