OOP Lec 7 (OperatorOverloading)
OOP Lec 7 (OperatorOverloading)
Example
Void operator ++()
{
function body ;
}
Overloading Unary Operators
• A type of operator that works with single operand is called unary
operand.
• The unary operators are overloaded to increase their capabilities.
• The unary operator that can be overloaded in C++are as follows:
+ - * ! ~ &
++ - - () -> new delete
Overloading ++ Operator
• The increment operator ++ is a unary operator.
• It works with single operand .
• It increase the value of operand by 1.
• It only works with numerical values by default.
• It can be overloaded to enable it to increase the values of data members of an
object in same way.
Write a program that overloads increment operator to work with user-defined objects
#include <iostream>
void operator ++()
using namespace std;
{
n=n+1;
class Count
}
{ };
private:
int n;
public: int main()
Count() {
{ Count obj;
n=0; obj.show();
} ++ obj;
void show() obj.show();
{
}
cout<<"n="<<n<<endl;
}
How Above Program Work
• The above program overloads the increment operator ++ to work with the
objects of all user-defined class count.
• It increases the value of data member n by 1.
• The user can use the same format to increase the value of object as used with
integers.
• The above overloading only works in prefix notation.
Operator Overloading with Returned Value
• The increment operator can be used in assignment statement to to store the
incremented value in another variable.
• Suppose a and b are two integers. The following statement will increment
the value of a by 1 and then assign the new value to b:
b= ++a;
{ x.in();
cout<<"Enter a:"; y.in();
cin>>a; z=x+y;
cout<<"Enter b:"; x.show();
cin>>b; y.show();
}
z.show();
void show()
return 0;
{
}
cout<<"a ="<<a<<endl;
cout<<"b ="<<b<<endl;
}
How Above Program Work
• The above program overloads the binary operator.
• When the binary object is used with objects, the left operand acts as calling
object and right operand acts as parameter passed to the function.
• z=x+y;
• In the above statement, x is the calling object and y is passed as parameter.
• The member function adds the value of calling object and parameter object.
• It stores the the result in a temporary object and the return the temporary
object.
• The return object is copied to the right side of assignment operator in main()
End of lecture