C++ Passing object and Returning object from function

Advertisements

C++ Returning object and Passing object as function argument

Object is a variable of class type. An object is used to access the class members. Like normal variable, object can be pass as function argument.

Example of Passing object & Returning object


	#include<iostream.h>
	#include<conio.h>

	class Rectangle
	{
		int L,B;

	Rectangle(int l,int b)
	{
		L = l;
		B = b;
	}

	Rectangle()
	{
		L = 0;
		B = 0;
	}

	Rectangle Sum(Rectangle Rec)        //function  1
	{

		Rectangle temp;

		temp.L = L + Rec.L;     //Statement  1
		temp.B = B + Rec.B;     //Statement  2

		return temp;
	}

	void Display()
	{
		cout<<"\nLength : "<<L;
		cout<<"\nBreadth : "<<B;
	}

	};

	void main()
	{

		Rectangle R1(5,7),R2(2,3),R3;

		cout<<"\n\nValues of Rectangle 1 : ";
		R1.Display();

		cout<<"\n\nValues of Rectangle 2 : ";
		R2.Display();

		R3 = R1.Sum(R2);     //Statement  3

		cout<<"\n\nValues of Rectangle 3 : ";
		R3.Display();
	}
	Output :

	Values of Rectangle 1 :
	Length : 5
	Breadth : 7

	Values of Rectangle 2 :
	Length : 2
	Breadth : 3

	Values of Rectangle 3 :
	Length : 7
	Breadth : 10

				

In statement 3, object R1 is calling member function Sum and passing object R2 as argument. Function 1 is receiving values of R2 in Rec. In statement 1 L is length of calling object R1 and Rec.L is length of object R2.

Both statement 1 and 2 is adding the length and breadth of Rectangle 1 and 2 respectively and assigning the result to object temp.

Statement 3 is receiving the values of object temp in object R3.

Advertisement