Object Object::Foo(); vs Object& Object:Foo()
What is the difference between returning and object and returning a reference to the object? If there is a difference, when would you use each case?
Printable View
Object Object::Foo(); vs Object& Object:Foo()
What is the difference between returning and object and returning a reference to the object? If there is a difference, when would you use each case?
The first returns a copy of a local object, the second returns a reference to a (possibly) local object. You should never return a reference to a local object, since it will fall out of scope at the end of the function and you'll have a reference to a destroyed object. You can return a reference when you are returning something that will not die in the scope of the function.
Here's an example of when you CAN return a reference:
It's common to return references in member operators, like;Code:class Object
{
private:
// store Object pointers to delete them later.
vector<Object*> myObjects;
public:
Object& Foo()
{
Object* o = new Object();
myObjects.push_back(o);
// since this was allocated with new,
// it will live past the end of this function
// until the Object that created it goes out of scope
// and the constructor below is called.
return (*o);
}
~Object()
{
while(myObjects.size() != 0)
{
delete myObjects.back();
myObjects.pop_back();
}
}
so that you can do something likeCode:class BigInt
{
public:
// assign *this = b; return (*this);
BigInt& operator=(const BigInt& b);
// assign *this = *this + b; return (*this);
BigInt& operator+=(const BigInt& b);
// assign *this = *this - b; return (*this);
BigInt& operator-=(const BigInt& b);
}
Code:BigInt a, b, c;
a = b = c; // (b = c) returns a reference to b, so that a = b.
thanks for clearing that up :)