Return objects from a function : return object « Function « C++ Tutorial






#include <iostream> 
using namespace std; 
 
class MyClass { 
  int val; 
public: 

  MyClass(int i) { 
    val = i; 
    cout << "Inside constructor\n"; 
  } 
 
  ~MyClass() { 
     cout << "Destructing\n"; 
  } 
 
  int getVal() { return val; } 
 
  // Return an object. 
  MyClass getDoubleValueClass() { 
    MyClass o(val * 2); 
 
    return o; 
  } 
}; 
 
void display(MyClass ob) 
{ 
  cout << ob.getVal() << '\n'; 
} 
 
int main() 
{ 
  cout << "Before constructing a.\n"; 
  MyClass a(10); 
  cout << "After constructing a.\n\n"; 
 
  cout << "Before call to display().\n"; 
  display(a); 
  cout << "After display() returns.\n\n"; 
 
  cout << "Before call to getDoubleValueClass().\n"; 
  a = a.getDoubleValueClass(); 
  cout << "After getDoubleValueClass() returns.\n\n"; 
 
  cout << "Before second call to display().\n"; 
  display(a); 
  cout << "After display() returns.\n\n"; 
 
  return 0; 
}
Before constructing a.
Inside constructor
After constructing a.

Before call to display().
10
Destructing
After display() returns.

Before call to getDoubleValueClass().
Inside constructor
Destructing
After getDoubleValueClass() returns.

Before second call to display().
20
Destructing
After display() returns.

Destructing








7.9.return object
7.9.1.Return objects from a function
7.9.2.A function may return an object to the caller