Operator Overloading DK Mamonai
Operator Overloading DK Mamonai
OPERATOR OVERLOADING.
Operator Overloading Operator overloading is one of the main feature of object oriented programming. The operator overloading means adding the functionality of the operators to the user defined data types. As suppose there are three variables a, b, & c all of type int then,
The Keyword Operator To teach the compiler that we are overloading we use the keyword operator in the decelerator of the member function in the class with the return type and the operator follows the keyword operator and at last the parenthesis come enclosing the arguments in to it like in below decelerator:
Overloading Unary Operators The unary operators are those which require one operand to operate. Like the increment and decrement operators.
Program (OptOver.cpp)
#include <constream.h> class Counter { private: int count; public: Counter(){count=0;} int get_count(){return count;} void operator ++(){++count;} }; void main() { Counter C1, C2; cout<<C1 = <<C1.get_count()<<endl; cout<<C2 = <<C2.get_count()<<endl; ++C1; ++C2; ++C2; cout<<C1 = <<C1.get_count()<<endl; cout<<C2 = <<C2.get_count()<<endl; getch(); }
In the above program the unary operator ++ is overloaded with the objects C1 and C2 in which it increments both the objects by the value of one as it does with other predefined data type.
====================================================================
Program (OptOver2.cpp)
#include <constream.h> class Counter { private: int count; public: Counter(){count=0;} int getcount(){return count;} void operator ++(){count--;} }; void main() { Counter C1, C2; cout<<C1.getcount()<<endl; cout<<C2.getcount()<<endl; int g=++C1; cout<<endl<<g; ++C2; ++C2; int h=C2; cout<<endl<<h; getch(); } ====================================================================