Operator Overloading In C++
Operators
to work for user defined classes. This means C++ has the ability to provide the
operators with a special meaning for a data type, this ability is known as
operator overloading.
Fig:Operator Overloading In C++ |
Rules of operator overloading
· In case of a non-static function,
the binary operator should have only one argument and unary should not have an
argument.
· In the case of a friend function,
the binary operator should have only two argument and unary should have only
one argument.
· All the class member object should
be public if operator overloading is implemented.
· Operators that cannot be overloaded
are . .* :: ?:
· Operator cannot be used to overload
when declaring that function as friend function = () [] ->.
Synatx:
class
baseclass
{
//body
of base
return
type operator++(argument)
{
}
return
type operator operator name(argument)
{
}
};
Program:
#include<iostream.h>
#include<conio.h>
class base
{
Int n;
public:
base()
{
n=0;
}
void operator++()
{
n=n-2;
}
Void operator—()
{
n=n+2;
}
void show()
{
cout<<”n=”<<n;
}
};
void main()
{
base obj;
obj.show();
++obj;
obj.show();
++obj;
obj.show();
--obj;
obj.show();
--obj;
obj.show();
getch();
}
Output:
n=0
n=-2
n=-4
n=-2
n=0
No comments:
Post a Comment