Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I was learning about returning by reference, and I have two questions and I wish I could find their answers here.

The first : does returning by reference means returning the address of the object so returning the actual object, while returning by value means returning the value which the object carries ?

The second - which may be connected strongly to the first even the same!! - why this code does not work ?
C++
#include <iostream>

using namespace std;

class foo
{
public :
    foo() {}
    foo(int myInt) : i(myInt) {}
    foo(foo& f) : i(f.i) {}

    int i;
};

foo someWork()
{
    foo* pFoo = new foo(5050);
    return *pFoo;
}

int main()
{
    foo myFoo( someWork() );
    cout << myFoo.i;
}

It works by changing the return type of someWork() to a reference to object but returning the same object it does not !!
So could you explain that to me, please ?

Thanks, Sam.
Posted
Comments
Sergey Alexandrovich Kryukov 28-Jul-15 23:38pm    
In your code samples, you never return anything returning a reference or through passing parameters by reference, so what are you talking about?
I don't know why should you return an object reference — it depends on what you want to achieve.
—SA

1 solution

Please see my comment to the question. Unfortunately, it neither seems to be clear nor quite correct.

To understand what return of the reference does, you may want to see these articles and analyze the code samples shown:
https://msdn.microsoft.com/en-us/library/z0c3dx2s.aspx[^],
http://www.tutorialspoint.com/cplusplus/returning_values_by_reference.htm[^].

I think everything is clear here, but if you think it's not, perhaps you fist should read on C++ references in general, for example, here: https://msdn.microsoft.com/en-us/library/dz43scw4.aspx[^],
http://www.tutorialspoint.com/cplusplus/cpp_references.htm[^],
http://www.cprogramming.com/tutorial/references.html[^],
https://en.wikipedia.org/wiki/Reference_%28C%2B%2B%29[^].

As references is majorly a syntactic feature which can be expressed in terms of pointers, which can give you equivalent machine code (object and executable), references provide purely syntactic benefits and additional safety stemmed from those syntactic benefits. For example, with by-reference function parameters, you can exclude appearance of null, which cannot be enforced with pointers.

—SA
 
Share this answer
 
v3
Comments
Samuel Shokry 29-Jul-15 13:22pm    
Thanks you helped me.
Sergey Alexandrovich Kryukov 29-Jul-15 14:15pm    
You are very welcome.
Good luck, call again.
—SA
Samuel Shokry 29-Jul-15 23:17pm    
I will.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900