A function can also return objects either by value or by reference. When an object is returned by value from a function, a temporary object is created within the function, which holds the return value. This value is further assigned to another object in the calling function.
The syntax for defining a function that returns an object by value is
class_name function_name (parameter_list)
// body of the function
To understand the concept of returning an object by value from a function, consider this example.
Example: A program to demonstrate the concept of returning objects from a function
void getdata ();
void putdata ();
void sum_weight (weight,weight) ;
weight sum_weight (weight) ;
void weight :: getdata()
void weight :: putdata ()
cout<<kilogram<<" Kgs. and"<<gram<<" gros.\n";
weight weight :: sum_weight(weight w2)
temp.gram = gram + w2.gram;
int main ()
weight w1,w2 ,w3;
cout<<"Enter weight in kilograms and grams\n";
cout<<"\n Enter weight #1" ;
cout<<" \n Enter weight #2" ;
cout<<"/n Weight #1 = ";
cout<<"Weight #2 = ";
cout<<"Total Weight = ";
As the return type of function is weight (an object of class weight), a temporary object temp is created within the function for holding return values. These values are accessed as temp kilogram and temp gram by the function. When the control returns to main (), the object temp is assigned to the object w3 in main( ).
Figure represents accessing of member variables within the function and returning a result from the temporary object.
In the case of returning an object by reference, no new object is created, rather a reference to the original object in the called function is returned to the calling function.
The syntax for defining a function that returns an object by reference is
class_name& function_name (parameter_list)
//body of the function
However, a reference to the local object (object declared inside the function) cannot be returned from the function since a reference to local data points to data within the function. Hence, when the function terminates and local data is destroyed, this reference points to nothing.
To understand this concept, consider the function sum_weight () that is modified as shown in this code segment..
weight& weight::sum_weight(weight & w2)
weight temp; //object local to function
return temp; //invalid
In this code segment, an attempt has been made to return the reference to an object of type weight (that is temp).However, it is not possible as the object temp is local to the sum_weight()function and a reference to this object remains effective only within the function. Thus, returning the reference to temp object outside the function generates a compile-time error.