Operator Overloading
Operator Overloading
OPERATOR OVERLOADING
• The “mechanism of giving such special meanings to
an operator is known as operator overloading.”
2
•Precedence of an operator cannot be changed
3
RESTRICTIONS ON OPERATOR OVERLOADING
4
Syntax:
return_type operator op(parameters);
GENERAL FORMAT
•op is the operator being overloaded
•op is preceded by the keyword operator which is the
function name
5
•Operator functions as member functions
6
• Operator that takes single operand in an expression
or statement
7
#include <iostream>
using namespace std;
class space
{
int x,y,z;
EXAMPLE
public:
void getdata(int a,int b,int c);
void display(void);
void operator-(); //Overloading unary minus
};
8
void space :: getdata(int a,int b,int c)
{
x=a; y=b; z=c;
}
void space :: display (void)
{
EXAMPLE
cout << x << " ";
cout << y << " ";
cout << z << "\n";
}
void space :: operator-() //Defining operator-()
{
x=-x; y=-y; z=-z;
}
9
int main ()
{
space S;
S.getdata(5,-15,25);
cout << "Value before overloading" << "\n";
cout << "S =";
EXAMPLE
S.display();
-S; //activates operator-()
cout << "Value after overloading" << "\n";
cout << "S =";
S.display();
return 0;
}
10
#include <iostream>
counter operator ++ ( )
using namespace std; {
class counter count++;
{ counter temp;
int count; temp.count = count;
public: return temp;
EXAMPLE
counter( ) }
{ };//class end
count = 0;
}
int getcount( )
{
return count;
}
11
int main( )
{
counter c1,c2;
cout<<"\nc1="<<c1.getcount( );
cout<<"\nc2="<<c2.getcount( );
++ c1;
EXAMPLE
c2=++c1;
cout<<"\nc1="<<c1.getcount( );
cout<<"\nc2="<<c2.getcount( );
return 0;
}
12
PROBLEM:
17
int main()
{
18
EXAMPLE USIING MEMBER FUNCTION
19
• We can use a friend function with a built-in type data
22
vector operator *(int a, vector b)
{ vector c;
26