Lesson 7 | Unary and binary operator overloading |
Objective | Difference between overloading Unary and Binary Operators |
Difference between overloading Unary and Binary Operators in C++
Unary and binary operators can be overloaded as
nonstatic member functions. Implicitly they are acting on a class value.
Unary operators can be overloaded as ordinary functions that take a single argument of class or reference to class type.
Binary operators can be overloaded as ordinary functions that take one or both arguments of class or reference to class type. In the next several lessons, we will look closely at overloading both unary and binary operators.
Take a look at the following unary operator overloading example, in this case the unary operators increment (++) and decrement (--):
//Increment and decrement overloading
class Inc {
private:
int count ;
public:
Inc() {
//Default constructor
count = 0 ;
}
Inc(int C) {
// Constructor with Argument
count = C ;
}
Inc operator ++ () {
// Operator Function Definition
return Inc(++count);
}
Inc operator -- () {
// Operator Function Definition
return Inc(--count);
}
void display(void) {
cout << count << endl ;
}
};
void main(void) {
Inc a, b(4), c, d, e(1), f(4);
cout <<"Before using the operator ++()\n";
cout << "a = ";
a.display();
cout << "b = ";
b.display();
++a;
b++;
cout << "After using the operator ++()\n";
cout << "a = ";
a.display();
cout << "b = ";
b.display();
c = ++a;
d = b++;
cout << "Result prefix (on a) and postfix (on b)\n";
cout << "c = ";
c.display();
cout << "d = ";
d.display();
cout << "Before using the operator --()\n";
cout << "e = ";
e.display();
cout << "f = ";
f.display();
--e;
f--;
cout << "After using the operator --()\n";
cout << "e = ";
e.display();
cout << "f = ";
f.display();
}