How to return a class object by reference in C++?

user788171 picture user788171 · Jan 18, 2012 · Viewed 106.5k times · Source

I have a class called Object which stores some data.

I would like to return it by reference using a function like this:

    Object& return_Object();

Then, in my code, I would call it like this:

    Object myObject = return_Object();

I have written code like this and it compiles. However, when I run the code, I consistently get a seg fault. What is the proper way to return a class object by reference?

Answer

Chowlett picture Chowlett · Jan 18, 2012

You're probably returning an object that's on the stack. That is, return_Object() probably looks like this:

Object& return_Object()
{
    Object object_to_return;
    // ... do stuff ...

    return object_to_return;
}

If this is what you're doing, you're out of luck - object_to_return has gone out of scope and been destructed at the end of return_Object, so myObject refers to a non-existent object. You either need to return by value, or return an Object declared in a wider scope or newed onto the heap.