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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With