Passing Object as argument:
An object can be passed into function as function argument like normal variables. This is illustrated from following example. This example shows addition of two complex numbers.
#include<iostream.h>
#include<conio.h>
class complex
{
private:
int real, imj;
public:
void get_complex();
void add_complex(complex, complex);
void display_complex();
};
void complex:: get_complex()
{ cout<<"Real part:\t";
cin>>real;
cout<<"\nImj Part:\t";
cin>>imj; }
void complex::display_complex()
{ cout<<"The sum is:\t" ;
cout<<real<<"+j"<<imj; }
void complex::add_complex( complex c1, complex c2)
{ real=c1.real+c2.real;
imj=c1.imj+c2.imj; }
void main()
{
complex first, second, result;
clrscr();
cout<<"\nEnter first complex number\n";
first.get_complex();
cout<<"\nEnter second complex number\n";
second.get_complex();
result.add_complex(first,second); //objects first and second passed as argument
result.display_complex();
getch();
}
Output:
Enter first complex number
Real part: 2
Imj Part: 4
Enter second complex number
Real part: 1
Imj Part: 8
The sum is: 3+j12
No comments:
Post a Comment