Your options are to return by value or to return a reference/pointer to a heap-based object.
Return by value
Changing your function signature to this
Test returnval()
will copy obj
. Note that the pointers you print out may still have the same value for the object inside the class and the object outside, as the compiler may have performed a return value optimisation.
If the Test
class is not managing dynamically allocated resources, then you can rely on the automatically created copy constructors that the compiler will inject. If Test
has dynamically allocated data, then you must write your own. See What is the Rule of Three?.
Return a pointer (or reference) to a heap-based object
You can change it to a heap-based object by using new
, and then return a pointer instead:
Test* returnptr(){
Test* obj = new Test(9,9);
cout << "in function: " << obj << endl;
return obj;
}
Or better yet, a smart pointer like shared_ptr to manage the deletion for you:
shared_ptr<Test> returnptr() {
// Wrapping the pointer in a shared_ptr will ensure it gets cleaned
// up automatically when the last reference to it (usage of it)
// goes out of scope.
shared_ptr<Test> obj(new Test(9,9));
cout << "in function: " << obj.get() << endl;
return obj;
}
Final note
As pointed out by one of the commenters on my answer, in C++11, you have further options to control how the temporary object from your function is returned by providing move constructors for Test
and using std::move
as necessary. This is a fairly meaty subject, but you can read more about it at the following links: