How to return an object to a function in C++?

When function returns an object a temporary object is automatically created which has the return value. After returning the value temporary object is destroyed.

For Example:

#include <iostream>

using namespace std;

class test {

int a;


void set_a(int b) { a=b; }

int get_a() { return a; }


test f();

int main()


test o;

o = f();

cout << o.get_a() << “\n”;

return 0;


test f()


test x;


return x;


Leave a Reply