The unary operators operate on a single operand and following are the examples of Unary operators:
The increment (++) and decrement (--) operators.
The unary minus (-) operator.
The logical not (!) operator.
The unary operators operate on the object for which they were called and normally, this operator
appears on the left side of the object, as in !obj, -obj, and ++obj but sometime they can be used as
postfix as well like obj++ or obj--.
Following example explain how minus (-) operator can be overloaded for prefix as well as postfix
usage.
#include <iostream>
using namespace std;
class Distance
{
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
// method to display distance
void displayDistance()
{
cout << "F: " << feet << " I:" << inches <<endl;
}
// overloaded minus (-) operator
Distance operator- ()
{
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
};
int main()
{
Distance D1(11, 10), D2(-5, 11);
-D1; // apply negation
[Link](); // display D1
-D2; // apply negation
[Link](); // display D2
return 0;
}
When the above code is compiled and executed, it produces the following result:
F: -11 I:-10
F: 5 I:-11
The increment (++) and decrement (--) operators are two important unary operators available in C++.
Following example explain how increment (++) operator can be overloaded for prefix as well as postfix
usage. Similar way, you can overload operator (--).
#include <iostream>
using namespace std;
class Time
{
private:
int hours; // 0 to 23
int minutes; // 0 to 59
public:
// required constructors
Time(){
hours = 0;
minutes = 0;
}
Time(int h, int m){
hours = h;
minutes = m;
}
// method to display time
void displayTime()
{
cout << "H: " << hours << " M:" << minutes <<endl;
}
// overloaded prefix ++ operator
Time operator++ ()
{
++minutes; // increment this object
if(minutes >= 60)
{
++hours;
minutes -= 60;
}
return Time(hours, minutes);
}
// overloaded postfix ++ operator
Time operator++( int )
{
// save the orignal value
Time T(hours, minutes);
// increment this object
++minutes;
if(minutes >= 60)
{
++hours;
minutes -= 60;
}
// return old original value
return T;
}
};
int main()
{
Time T1(11, 59), T2(10,40);
++T1; // increment T1
[Link](); // display T1
++T1; // increment T1 again
[Link](); // display T1
T2++; // increment T2
[Link](); // display T2
T2++; // increment T2 again
[Link](); // display T2
return 0;
}
When the above code is compiled and executed, it produces the following result:
H: 12 M:0
H: 12 M:1
H: 10 M:41
H: 10 M:42
/* Simple example to demonstrate the working of operator overloading*/
#include <iostream>
using namespace std;
class temp
{
private:
int count;
public:
temp():count(5){ }
void operator ++() {
count=count+1;
}
void Display() { cout<<"Count: "<<count; }
};
int main()
{
temp t;
++t; /* operator function void operator ++() is called */
[Link]();
return 0;
}
Output
Count: 6
Explanation
In this program, a operator function void operator ++ () is defined(inside class temp), which
is invoked when ++ operator operates on the object of type temp. This function will increase
the value of count by 1.
Things to remember while using Operator overloading in
C++ language
1. Operator overloading cannot be used to change the way operator works on built -in types. Operator
overloading only allows to redefine the meaning of operator for user -defined types.
2. There are two operators assignment operator(=) and address operator(&) which does not need to be
overloaded. Because these two operators are already overloaded in C++ library. For example:
Ifobj1 and obj2 are two objects of same class then, you can use code obj1=obj2; without
overloading = operator. This code will copy the contents object of obj2 to obj1. Similarly, you can
use address operator directly without overloading which will return the address of object in
memory.
3. Operator overloading cannot change the precedence of operators and associativity of operators. But,
if you want to change the order of evaluation, parenthesis should be used.
4. Not all operators in C++ language can be overloaded. The operators that cannot be overloaded in
C++ are ::(scope resolution), .(member selection), .*(member selectio n through pointer to function)
and ?:(ternary operator).
Following best practice while using operator overloading
Operator overloading allows programmer to define operator the way they want but, there is
a pitfall if operator overloading is not used properly. In above example, you have seen ++
operator operates on object to increase the value of count by 1. But, the value is increased
by 1 because, we have used the code:
void operator ++() {
count=count+1;
If the code below was used instead, then the value of count will be decreased by 100 if ++
operates on object.
void operator ++() {
count=count-100;
But, it does not make any sense to decrease count by 100 when ++ operator is used.
Instead of making code readable this makes code obscure and confusing. And, it is the job
of the programmer to use operator overloading properly and in consistent manner.
Again, the above example is increase count by 1 is not complete. This program is
incomplete in sense that, you cannot use code like:
t1=++t
It is because the return type of operator function is void. It is generally better to make
operator work in similar way it works with basic types if possible.
Here, are the examples of operator overloading on different types of opera tors in C++
language in best possible ways:
Increment and Decrement Operator Overloading
Overloading of binary operator - to subtract complex number
Binary Operator Overloading to Subtract Complex
Number
/* C++ program to demonstrate the overloading of binary operator by subtracting one complex number
from another. */
#include <iostream>
using namespace std;
class Complex
{
private:
float real;
float imag;
public:
Complex(): real(0), imag(0){ }
void input()
{
cout<<"Enter real and imaginary parts respectively: ";
cin>>real;
cin>>imag;
}
Complex operator - (Complex c2) /* Operator Function */
{
Complex temp;
[Link]=[Link];
[Link]=[Link];
return temp;
}
void output()
{
if(imag<0)
cout<<"Output Complex number: "<<real<<imag<<"i";
else
cout<<"Output Complex number: "<<real<<"+"<<imag<<"i";
}
};
int main()
{
Complex c1, c2, result;
cout<<"Enter first complex number:\n";
[Link]();
cout<<"Enter second complex number:\n";
[Link]();
/* In case of operator overloading of binary operators in C++ programming, the object on right hand
side of operator is always assumed as argument by compiler. */
result=c1-c2; /* c2 is furnised as an argument to the operator function. */
[Link]();
return 0;
}
In this program, three objects of type Complex is created and user is asked to enter the real
and imaginary parts for two complex numbers which is stored in objects c1 and c2 . Then
statement result=c1-c2 is executed. This statement invokes the operator function Complex
operator - (Complex c2) . When result=c1-c2 is executed, c2 is passed as argument to
the operator function. In case of operator overloading of binary operators in C++
programming, the object on right hand side of operator is always assumed as argument by
compiler. Then, this function returns the resultant complex number (object) to main ()
function and then, it is displayed.
Though, this tutorial contains the overloading of - operators, binary operators in C++
programming like: +, *, <, += etc. can be overloade d in similar manner.