All About C++

Get Pure Concepts of C++

Saturday, 4 June 2016

How to pass objects as parameters in the function with code example

We can pass objects as parameter in the functions.to use objects as parameter, we just pass the object’s name as in the case of array.
Let a1 and a2 are two objects and “add” is a function name then we will pass these objects as parameters as
add(a1,a2);
When we make function to pass objects as parameter then the data types of function attribute must be the name of that class in which we are making that function.
I explain this concepts using a complete code example
This code add, subtract and multiply two objects values

#include<iostream>
#include<math.h>
using namespace std;
class complex
{
private:
            float real;
            float imaginary;
public:
            complex():real(0),imaginary(0)
            {}
complex(float re,float im):real(re),imaginary(im)
{}
void add(complex a,complex b)
{float z;
            float x,y,k;
            z=a.real+b.real;
            x=-(a.imaginary);
            y=-(b.imaginary);
            k=sqrt(x)+sqrt(y);
            cout<<endl<<"addition is  "<<z<<"+"<<k<<"i"<<endl;
}
void subtruct(complex s,complex w)
{float z;
            float x,y,k;
            z=s.real-w.real;
            x=-(s.imaginary);
            y=-(w.imaginary);
            k=sqrt(x)-sqrt(y);
            cout<<endl<<"subtrucrtion is  this"<<endl<<z;
if(k>=0)
{cout<<"+"<<k<<"i"<<endl;}
else
{cout<<"-"<<k<<"i"<<endl;}}
void product(complex f1,complex f2)
{float z;
            float x,y,k,o,t,r1,r2;
            z=f1.real*f2.real;
            x=-(f1.imaginary);
                        y=-(f2.imaginary);
                        k=(f1.real)*(sqrt(y));
                        o=(f2.real)*(f1.imaginary);
                        t=x*y;
                        r1=z+t;
                        r2=k+o;
                        cout<<endl<<"production is this   "<<r1;
                        if(r2>=0)
                        {
                                    cout<<"+"<<r2<<endl;}
                        else
                        {cout<<"-"<<r2<<endl;}}
void getdata()
{
cout<<"enter real and imaginary  ";
            cin>>real>>imaginary;}
};
void main()
{
             complex i(12.2,-25.3);
            complex e1,e2,e3,e4;
            e1.getdata();
            e2.add(i,e1);
            e3.subtruct(i,e1);
            e4.product(i,e1);
             system("pause");}

Here:
void add(complex a,complex b);
void subtruct(complex s,complex w);
void product(complex f1,complex f2);

These are the function declaration method to use objects as parameters and here complex is the name of class in which these functions are made.

And
            e2.add(i,e1);
            e3.subtruct(i,e1);
            e4.product(i,e1);
Here functions are called in which objects are passed as parameters;
Here i, e1, e2 and e3 are objects names.








No comments:

Post a Comment