Advance C++


C++ Returning object from a function tutorials
-
As we have seen in structures, object can be returned from the function. Only assignment operation is possible on objects, hence call statements must be in assignment and not in any other form.
Program to return an object using member functions |
|
|
//WAP to return an object using member functions#include <iostream.h>#include <conio.h>class dist{private:intft;float inch;public:void input(){cout<<endl<<"Enter feet and inches: ";cin>>ft>>inch;}dist add(dist);void display(){cout<<ft<<" ft "<<inch<<" inches";}};void main(){distx,y,z;x.input();y.input();z=x.add(y);cout<<endl<<"Total distance = ";z.display();}distdist::add(dist d){dist x;x.ft=ft+d.ft;x.inch=inch+d.inch;if (x.inch>=12){x.ft++;x.inch-=12;}return x;} |
Output |
Enter feet and inches: 3 4Enter feet and inches: 7 8Total distance = 11 ft 0 inches |
-
Here the return type of add() is dist. Hence the definition contains dist twice. First is return type and second is class name to which the function belongs. Function add() is called for x and y is sent as argument. Function creates own object to store sum. This object is returned and assigned to z from main().