Monday 6 April 2015

Operator overloading with Friend Function

#include <iostream.h>
class complex
{
private:

float real;
float imag;

public:

complex()
{
real = imag = 0.0;
}
void getdata(void)
{
cout<<”Real Part ?”;
cin>>real;
cout<<”Imag Part ?”;
cin>>imag;
}
void outdata(char *msg)
{
cout<<msg;
cout<<”(“<<real;
cout<<”, “<<imag<<endl;
}
friend complex operator – (complex c1)
{
complex c;
c.real = -c1.real;
c.imag = -c1.imag;
return (c);
}
};
void main()
{
complex c1, c2;
cout<<”Enter complex c1…”<<endl;
c1.readdata();
c2 = -c1;
c1.outdata(“Complex c1:”);
c2.outdata(“Complex c2 = - Complex c1:”);
}
Note :

Friend functions offer the flexibility of writing an expression as a combination of operands of user defined and primitive data types. For instance, consider the statement.

C3 = c1 + 2.0;

The expression is made up of the object c1 and a primitive type. In case of an operator member function, both the operands must be of object’s data type. When the friend operator functions are used, both the operands need not be instances of user-defined data type. It requires a parameterized constructor tak ing a primitive data type parameter.

#include <iostream.h>
class complex
{
private:
float real;
float imag;
public:
complex()
{}
complex(int realpart)
{
real = realpart;
}
void readdata(void)
{
cout<<”Real Part ?”:
cin>>real;
cout<<”Imag Part ?”:
cin>>imag;
}
void outdata(char *msg)
{
cout<<endl<<msg;
cout<<”(“<<real;
cout<<”, “<<imag<<”)”;
}
friend complex operator + (complex c1, complex c2);
};
complex operator +(complex c1, complex c2)
{
complex c;
c.real = c1.real + c2.real;
c.imag = c1.imag + c2.imag;
return (c);
}
void main()
{
complex c1, c2, c3 = 3.0;
cout<<”Enter complex c1…”<<endl;
c1.readdata();
cout<<”Enter Complex c2….”<<endl;
c2.readdata();
c3.outdata(“Result of C3 = c1 + c2”);
c3 = c1+ 2.0; // c3 = c1.complex(2.0);
c3.outdata(“Result of c3 = c1 + 2.0”);
c3 = 3.0 + c2;
c3.outdata(“Result of c3 = 3.0 + c2);
}
the statement
c3 = c1 + 2.0;

has an expression which is a combination of the object c1 and the primitive floating point constant 2.0. though, there is no member function matching this expression, the compiler will resolve this by treating the expression as follows:

c2 = c1 + complex(2.0);

the compiler invokes the single argument constructor and converts the primitive values to a new temporary object and passes it to the friend operator function.

No comments:

Post a Comment