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?
"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.
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.
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.
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();
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 new
ed onto the heap.
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