[oop - lec 16,17] objects as function parameter and returntype
TRANSCRIPT
Objects as Function Parameters & Return
TypeMuhammad Hammad [email protected]
Object as Function Parameters• Objects can also be passed as parameters to member functions.• The method of passing objects to a functions as parameters is as
passing other simple variables.• It will easily be understand by following example.
Exampleclass Travel{ private: int km, hr; public:Travel() { km=hr=0; }void get() { cout<<“Enter Kilometers traveled”;cin>>km; cout<<“Enter Hours traveled”;cin>>hr; }void show() { cout<<“You traveled ”<<km<<“ in ”<<hr<<“ hours”<<endl; }
void add(Travel p) {Travel t; t.km=km+p.km; t.hr=hr+p.hr;cout<<“Total traveling is ”<<t.km<<“ kilometers in ”<<t.hr<<“ hours”<<endl;}};void main(){ Travel my, your;my.get(); my.show();your.get(); your.show();my.add(your);getch();}
How Program Works• The above program declares to objects of class Travel and inputs data in both objects.• The add() function accepts an object of type Travel as parameter.• It adds the values of data members of the parameter object and the values of calling object’s data
members and displays the result.• The working of member function add() is as follows:void add(Travel p) {Travel t; t.km = km + p.km; t.hr = hr + p.hr;}• Data members of temporary object t• Data members of temporary object my• Data members of temporary object p
Function call in mainmy.add(your);
Returning Objects from Member Function• The method of returning an object from member function is same as
returning a simple variable.• If a member function returns an object, its return type should be the
same as the type of object to be returned.
Exampleclass Travel{ private: int km, hr; public:Travel() { km=hr=0; }void get() { cout<<“Enter Kilometers traveled”;cin>>km; cout<<“Enter Hours traveled”;cin>>hr; }void show() { cout<<“You traveled ”<<km<<“ in ”<<hr<<“ hours”<<endl; }
Travel add(Travel p) {Travel t; t.km=km+p.km; t.hr=hr+p.hr;return t;} };void main() { Travel my, your, r;my.get(); my.show();your.get(); your.show();r = my.add(your);cout<<“Total travelling is as follow:\n”;r.show(); getch();}
How Program Works• The add() function in the above program accepts a parameter object
of type Travel.• It adds the contents of parameter and calling object and stores the
result in a temporary object.• The function then returns the whole object back to main() function
that is stored in r.• The program finally displays the result using r.show() statement.