Introduction Rules Types Programs OPERATOR OVERLOADING Introduction Rules Types Programs
Introduction Allows us to define the behavior of operators when applied to objects of a class Operator Overloading does not allow us to alter the meaning of operators when applied to built-in types Example: 2+3 addition, 2*3 multiplication By operator overloading, we can apply the operators to our own abstract data type like this Example; Class A{ int a,b; public: A(int x,int y){a=x;b=y;} }; main() { A obj1(2,3); -obj1; }
To Overload an Operator Steps Overloading an operator Write function definition as normal Function name : operator keyword followed by the symbol Operator+ () Applying operators on objects Create objects for the class Apply the operator on objects object1 + object2 -object1
Rules to Overload an operator Precedence of an operator cannot be changed Associativity of an operator cannot be changed Arity (number of operands) cannot be changed No new operators can be created ( Ex: +-) Use only existing operators No overloading operators for built-in types Cannot change how two integers are added Produces a syntax error (Ex; 2+3) Operator functions can be member or non- member functions
Rules to Overloade an operator C++ operators that can be overloaded C++ Operators that cannot be overloaded
Types Syntax Return type class name :: operator symbol(args){ } Using Member Function Unary Operator Overloading Ex: A operator –() ( ) Binary Operator Overloading Ex: A operator –(A object) ( ) Using Non Member Function (use Friend Keyword) Ex: A operator –(A object1, A object2) ( )
Unary operator : Member Function class A { int inches,feet; public: A(int x,int y) { inches=x; feet=y; } void display() { cout <<"\n"<<inches<<" "<<feet;} void operator-() { inches=-inches; feet=-feet; } }; int main() { A obj1(20,10); obj1.display(); -obj1; }
Binary operator Using Member Function class A { int a,b; public: A(int x,int y) { a=x; b=y; } void display() { cout <<"\n"<<inches<<" "<<feet;} void operator+(A o1); }; Void A :: operator +(A o1) a=a+o1.a; b=b+o1.b; }
int main() { A obj1(20,10); A. obj2(10,20); obj1+obj2; obj1 int main() { A obj1(20,10); A.obj2(10,20); obj1+obj2; obj1.display(); }
Unary operator : Non Member Function class A { int a,b public: A() { a=b=0; } A(int x,int y) { a=x; b =y; } void display() { cout <<"\n"<<a<<" "<<b;} friend A operator-(A) }; A operator-(A d1) A d2; d2.a=-d1.a; d2.b=-d1.b; return d2; } ;
int main() { A obj1(20,10); obj1.display(); A C; C=-obj1; C.display(); }
Unary operator : Non Member Function class A { int a,b public: A() { a=b=0; } A(int x,int y) { a=x; b =y; } void display() { cout <<"\n"<<a<<" "<<b;} friend A operator+(A,A) }; A operator+(A d1,A d2) A d3; d3.a=-d1.a+d2.a; d3.b=-d1.b+d2.b; return d3; } ;
int main() { A obj1(20,10); A obj2(20,10); obj1.display(); Obj2.display(); A C; C=obj1+obj2; C.display(); }