Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 833
user788171 Avatar asked Jan 18 '12 17:01

user788171


People also ask

How do you pass a class object by reference?

"reference" is a widely used programming term that long predates the C++ standardizing of it. Passing a pointer to an object is passing that object by reference. According to Benjamin: If you have a pointer, e.g. int *a, then *a is precisely a reference.

How do I return a class object?

If a method or function returns an object of a class for which there is no public copy constructor, such as ostream class, it must return a reference to an object. Some methods and functions, such as the overloaded assignment operator, can return either an object or a reference to an object.

How do you pass an object by reference in a function?

Pass by reference in C++ The call by reference method is useful if you need to reflect on the changes done by a function. You can use a return statement if the function makes changes in exactly one parameter. But if multiple parameters are affected then call by reference will be useful.

How do you return a class object in C++?

Example 2: C++ Return Object from a Function In this program, we have created a function createStudent() that returns an object of Student class. We have called createStudent() from the main() method. // Call function student1 = createStudent();


1 Answers

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.

like image 62
Chowlett Avatar answered Sep 20 '22 01:09

Chowlett