Returning objects. : Function Return « Function « C++






Returning objects.

Returning objects.

 
#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; 
  } 
  
  MyClass mkBigger() { 
    MyClass o(val * 2); 
 
    return o;              // Return an object. 
  } 
}; 
 
void display(MyClass ob) 
{ 
  cout << ob.getval() << '\n'; 
} 
 
int main() 
{ 
  cout << "Before constructing a.\n"; 
  MyClass a(10); 
  cout << "After constructing a.\n"; 
 
  cout << "Before call to display().\n"; 
  display(a); 
  cout << "After display() returns.\n"; 
 
  cout << "Before call to mkBigger().\n"; 
  a = a.mkBigger(); 
  cout << "After mkBigger() returns.\n"; 
 
  cout << "Before second call to display().\n"; 
  display(a); 
  cout << "After display() returns.\n"; 
 
  return 0; 
} 



           
       








Related examples in the same category

1.Returning a Value from a FunctionReturning a Value from a Function
2.Return Value Of FunctionsReturn Value Of Functions