Operator Overloading | OOP in C++


Operator overloading


Operator overloading feature of c++ assigns a new meaning to the existing operators, but original meaning cannot be changed.


Unary operator overloading


class rev_sign
{
int a, b, c;
public:
void getdata(int x, int y, int z)
{
a=x; b=y; c=z;
}
void show(void)
{
cout<<"\nA="<<a;
cout<<"\nB="<<b;
cout<<"\nC="<<c;
}
void operator-(void)
{
a=-a; b=-b; c=-c;
}
};
int main()
{
rev_sign t;
t.getdata(-7,6-9);
cout<<"\n t="; t.show();
-t; //t- not allowed
cout<<"\n t"; t.show();
}
Output:


Overloading Binary Operator


class complex
{
float x, y;
public:
complex(){}
complex(float a, float b)
{x=a; y=b;}
complex operator+(complex);
void display(void)
{
cout<<"\n"<<x<<"+j"<<y;
}};
complex complex::operator+(complex c)
{
complex t;
t.x=x+c.x;
t.y=y+c.y;
return t;
}
int main()
{
complex c1, c2, c3;
c1=complex(7.5, 2.5);
c2=complex(1.2, 1.3);
c3=c1+c2;
cout<<"\n c1="; c1.display();
cout<<"\n c2=";
c2. display();
cout<<"\n c3="
c3.display();
return 0;
}

Output:


Rules for overloading operators


1. Only existing operators can be overloaded.
2. The overloaded operator must have at least one operand.
3. We cannot change the basic meaning of an operator.
4. Overloaded operator follow the syntax rule of the original operator.
5. These operators cannot be overloaded:
Sizeof- size of operator
• - membership "
•*- pointer to member "
::- scope resolution "
?:- conditional operator
6. A friend function cannot overload the following :
= - Assignment operator
() - function call"
[]- subscribing "
-> - class member access "
member function can overload them.
7. Binary operators, overloaded through member function takes one expliar argument whereas in case of friend function. It takes two explicit arguments.
8. Unary operators, overloaded through member function takes zero explicit argument whereas in case of friend function it takes one explicit argument.

Custom Search

%d bloggers like this: