Is it possible to return an object from a function? Justify your answer with an example.



Return of an Object from a Function: Yes it is possible to return an object from a function. An object can be returned to the call of its function by another object. For the justification considering the following program,


//Returning of object
#include<iostream.h>

class myclass{
 int i;    
 public:
  void set_i(int n){
  i=n; /*Ln 3*/ 
  }
 int get_i(){
  return i; /*Ln 6*/ 
  }
 };

/*
 *this f() is a global function of the type myclass. 
 *The type has been announced so that it can use variables
 *and functions of the class myclass. But it is not a 
 *member function of myclass
 */
myclass f(){
 myclass x;    
 x.set_i(5);     /*Ln 2*//*calling set_i()and also sending 5 to parameter*/ 
 return x;      /*Ln 4*///here returning ‘x’ to the caller object ‘o’
 }

int main(){
 myclass o; 
 o=f();     /*Ln 1*/ 
       /*calling f() and assigning the value returned by the function 
                 *to the object ‘o’. Here f() will return an object 
                 *which will set ‘i’ to 5. Thus, the ‘i’ 
                 *under the object ‘o’ will become 5.
                 */
                 
 cout<<o.get_i(); /*Ln 5*/
          /*calling get_i() by ‘o’ to return the value
                             *of ‘i’ kept under object ‘o’
                             */
 return 0;
 }


            Output: 5


           Explanations: In the above program in Ln 1 we have called the global function f() where the returned value of this function will be assigned to the declared object ‘o’. Now, in Ln 4, it can be seen that f() returning x after it has called set_i() where it sent 5 as value. Thus the value ‘i’ is now 5. Finally using Ln 5 and Ln 6 the value of ‘i’ under the object ‘o’ will be printed.


            Thus here the object of ‘x’ of function f() is getting set under the object ‘o’ of main(). Thus here the f() function is returning an object ‘x’. 

Recommended Recommends

Comments

Contact Us

Loading...