Overload Unary Operator using Member Function


Unary operator having one operand so generally we need to pass one argument to the operator function.
If you define operator function as a member function then it will accept no argument. Because the object that is used to invoke the operator function is passed implicitly to the operator function.
Consider following example to overload unary operator ++ using member function

#include <iostream.h>
class demo
{
int count;
public:
demo()
{
count=0;
}
void operator ++()
{
count++;
}

void display()
{
cout<<"Count="<<count<<endl;
}
};
int main()
{
demo d1;
++d1;
d1.display();
++d1;
d1.display();
return 0;
}
Output:
Count = 1
Count = 2


     

Overload Unary Operator using Friend Function


If you define operator function as a friend function then it will accept one argument. Because friend functions is not a member function so it is not invoked using object of the class. Thus we need to pass object as an argument explicitly.
Consider following example to overload unary operator ++ using friend function.

#include <iostream.h>
class demo
{
int count;
public:
demo()
{
count=0;
}
friend void operator ++(demo &d)
{
d.count++;
}

void display()
{
cout<<"Count="<<count<<endl;
}
};
int main()
{
demo d1;
operator ++(d1);
d1.display();
operator ++(d1);
d1.display();
return 0;
}
Output:
Count = 1
Count = 2

Download Projects


Download Programs