Operator overloading is one of the most exciting feature of object-oriented programming and this is included in cbse syllabus. Operator overloading provides normal C++ operators, such as +, -, * etc additional meanings when they are applied to user defined data types. Normally we know that operators like + works only with basic types like int, float etc. Using overloading we can apply these operators on objects also.
Here is one program to demonstrate operator overloading.
#include< iostream.h>
#include< conio.h>
class Count
{
private:
int count;
public:
Count ()
{
count=0;
}
int getCount ()
{
return count;
}
void operator ++ ()
{
count++;
}
};
void main ()
{
clrscr ();
Count c1, c2;
cout<< "\nc1="<< c1.getCount ();
cout<< "\nc2="<< c2.getCount ();
++c1;
++c2;
cout<< "\nc1="<< c1.getCount ();
cout<< "\nc2="<< c2.getCount ();
getch ();
}
The unary operator ++ acts on objects c1 and c2 because the keyword operator is used and which is a must to overload the ++ operator in the function operator ++ (). This syntax tells the compiler to call the member function whenever the operator ++ is encountered, provided the operand is of type Count, the class here. If the operator ++ is used on variables of predefined type like int or float then the compiler will use its built-in routine to increment the value of the variable of int or float type.
No comments:
Post a Comment