Passing Object As Argument in C++
Passing Object As Argument in C++
}
};
int main()
{
Complex c1,c2,c3;
c1.Read();
c2.Read();
c3.Add(c1,c2);
c3.Display();
return 0;
}
Output
Enter real and imaginary number respectively:
12
3
Enter real and imaginary number respectively:
2
6
Sum=14+9i
Returning Object from Function
The syntax and procedure to return object is similar to that of returning structure
from function.
{
private:
int real;
int imag;
public:
Complex(): real(0), imag(0) { }
void Read()
{
cout<<"Enter real and imaginary number respectively:"<<endl;
cin>>real>>imag;
}
Complex Add(Complex comp2)
{
Complex temp;
temp.real=real+comp2.real;
/* Here, real represents the real data of object c1 because this function is called using
code c1.Add(c2) */
temp.imag=imag+comp2.imag;
/* Here, imag represents the imag data of object c1 because this function is called
using code c1.Add(c2) */
return temp;
}
void Display()
{
cout<<"Sum="<<real<<"+"<<imag<<"i";
}
};
int main()
{
Complex c1,c2,c3;
c1.Read();
c2.Read();
c3=c1.Add(c2);
c3.Display();
return 0;
}
-----------------------------Passing Objects as Function arguments in C++
Passing Objects as Function arguments
Our next program adds some establishment to the classes.It also demonstrates some
new aspects of classes :constructor overloading,and more importent passing objects
as function arguments.Here some examples that will clear your idea about this topic
Here some examples of passing objects as function arguments , very simple ,very
easy
Here examples of multiplication and divide are discussed ,you can use any arithmetic
operator solve programmes
#include <iostream>
using namespace std;
class rational
Example # 1
{
private:
int num;
int dnum;
public:
rational():num(1),dnum(1)
{}
void get ()
{
cout<<"enter numerator";
cin>>num;
cout<<"enter denomenator";
cin>>dnum;
}
void print ()
{
cout<<num<<"/"<<dnum<<endl;
}
void multi(rational r1,rational r2)
{
num=r1.num*r2.num;
dnum=r1.dnum*r2.dnum;
}
};
void main ()
{
rational r1,r2,r3;
r1.get();
r2.get();
r3.multi(r1,r2);
r3.print();
}
........................................................................................................................................
...................................................
Examples # 2
#include <iostream>
using namespace std;
class rational
{
private:
int num;
int dnum;
public:
rational():num(1),dnum(1)
{}
void get ()
{
cout<<"enter numerator";
cin>>num;
cout<<"enter denomenator";
cin>>dnum;
}
void print ()
{
cout<<num<<"/"<<dnum<<endl;
}
void divide(rational r1,rational r2)
{
num=r1.num*r2.dnum;
dnum=r1.dnum*r2.num;
}
};
void main ()
{
rational r1,r2,r3;
r1.get();
r2.get();
r3.divide(r1,r2);
r3.print();
}