Overloading Unary Operators
Unary operators are the ones that operate on one operand, one such operator is the unary minus (-) operator which is used to change the sign of the operand it acts upon. This operator works well with basic data types such as int, float, etc.. In this section we will see how to overload this operator so that it can work the same way for user defined data types as it does for basic data types, i.e. change the sign of the operand.
The unary minus operator function does not take any arguments but it changes the sign of the data members of the object that calls this function. Since this function is a member function of the same class, it can directly access the members of the object that calls it.
Example: -S In the above statement, object S invokes the member function unary minus. In our example, the function will change the sign of all the data members of the object S.
A statement such as S1 = – S2 will yield a compiler error since our unary minus member function is not designed to return any value; however, with a little modification this function will be able to return values.
It is possible to overload a unary minus operator using a friend function as follows:
.cf { font-family: Lucida Console; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: green; }
.cb2 { color: blue; }
.cb3 { color: maroon; }
friend void operator -(space &s); //declaration
void operator -(space &s) //definition
{
s.x = -s.x;
s.y = -s.y;
s.z = -s.z;
}
Note: In the above example, we have received the operand by reference because we need to change the values of its data members, which would not be possible if we would receive the argument by value.
Sample Program
/*
* This program illustrates the overloading of the
* unary minus (-) operator.
* http://www.byteguide.com
*/
#include<iostream>
using namespace std;
class Minus
{
private:
int a, b, c ;
public:
Minus(int A, int B, int C)
{
a = A;
b = B;
c = C;
}
void display(void);
//********Declaration of the operator function**********
void operator - ( );
};
void Minus :: display(void)
{
cout << "t a = " << a << endl ;
cout << "t b = " << b << endl ;
cout << "t c = " << c << endl ;
}
//*********Definition of the operator function***********
inline void Minus :: operator - ( )
{
a = -a ;
b = -b ;
c = -c ;
}
//*************Main Function Definition***************
int main(void)
{
Minus M(5, 10, -15) ;
cout << "n Before activating operator - ( )n" ;
M.display( ) ;
-M ;
cout << "n After activating operator - ( )n" ;
M.display( ) ;
}
Output
Before activating operator - ( )
a = 5
b = 10
c = -15
After activating operator - ( )
a = -5
b = -10
c = 15
In this Series
- Introduction to operator overloading
- Overloading unary operators
- Overloading binary operators
Comments - No Responses to “Overloading Unary Operators”
Sorry but comments are closed at this time.