CPP Programming
About Lesson

The mechanism of assigning additional responsibility to existing operator is known as operator overloading.  We can overload all C++ operators except the following:

Class member access operators (. and .*)
Scope Resolution operator (::)
size operator(sizeof)
conditional operator (?:)

Operator Function
Operator overloading is done with the help of a special function called operator function.

General form of operator function is:
returnType classname::operator op(argList)
{
FunctionBody
}

where operator op is the name of the function.

Operator overloading process involves the following steps:

Create a class that defines the data type that is to be used in the overloading operation.
Declare the operator function operator op() in the public part of the class
Define the operator function.

//Overloading Unary Minus that changes sign of data items#include

#include

class space

{

int x,y,z;

public:

void getdata(int a,int b,int c);

void display(void);

void operator -();

};

void space::getdata(int a,int b,int c)

{

x=a;

y=b;

z=c;

}

void space::display(void)

{

cout<<”nValue of x is:”<<x;

cout<<”nValue of y is:”<<y;

cout<<”nValue of z is:”<<z;

}

void space::operator –()

{

&nbsp;      x=-x;

y= -y;

z= -z;

}

main()

{

clrscr();

space s;

s.getdata(10,-20,30);

cout<< “nInitial values of object are:”;

s.display();

-s;

cout<< “nAfter applying – operator, values of Object are:”;

s.display();

}

//Overloading Binary Operator +

#include

#include

class complex

{

float x,y;

public:

complex();

complex(float real, float imag)

{

x=real; y=imag;

}

complex operator +(complex);

void display(void);

};

complex complex:: operator +(complex c)

{

complex temp;

temp.x=x+c.x;

tem.y=y+c.y;

return(temp);

}

void complex::display(void)

{

cout<< x << “ +j” <<y<< “n”;

}

main()

{

clrscr();

complex c1,c2,c3;

c1=complex(2.5,3.5);

c2=complex(1.6,2.7);

c3=c1+c2;

cout<< “First Complex Number is:”; c1.display();

cout<< “Second Complex Number is:”; c2.display();

cout<< “Third Complex Number is:”; c3.display();

}

You cannot copy content of this page