Experiment No 6 - Operators Overloading in C++
Experiment No 6 - Operators Overloading in C++
OPERATORS
OVERLOADING IN C++
by: Dr. Ram Paul Hathwal
Dept of CSE, ASET, AUUP
The Increment and Decrement Department of Computer
Operators in C++ Science and Engineering
C++ operator overloading is one of the most powerful features of C++ that allows
a user to change the way the operator works.
The increment (++) and decrement (--) operators are two important unary operators
available in C++.
You can redefine or overload the function of most built-in operators in C++.
These operators can be overloaded globally or on a class-by-class basis.
Overloaded operators are implemented as functions and can be member functions
or global functions.
You overload the prefix increment operator ++ with either a nonmember function
operator that has one argument of class type or a reference to class type, or with a
member function operator that has no arguments 2
Why do we need Operator Department of Computer
overloading in C++? Science and Engineering
Operators in C++ like +, -, *, / can operate in datatypes like int, float, double etc
as predefined operational meanings.
But these operators can’t operate in user-defined datatypes like objects without
extension or adding some sort of code to alter their operational meaning.
Such a way of extending the operational functionality of certain operators in C++
is called operator overloading.
To extend the meaning of an operator, an operator function is defined with a
keyword operator followed by the operator symbol.
Note : If increment/decrement operators are used before variable, they are called
prefix operators i.e ++x. And if increment/decrement operators are used
after variable, they are called postfix operators i.e x++.
3
Prefix Increment Operator Department of Computer
Science and Engineering
#include <iostream>
using namespace std;
class Check {
private:
int i;
public:
Check(): i(0) { }
void operator ++() { ++i; }
void Display() { cout << "i=" << i << endl; } };
int main() {
Check obj;
// Displays the value of data member i for object obj
obj.Display();
// Invokes operator function
void operator ++( ) ++obj;
// Displays the value of data member i for object obj
obj.Display();
return 0;
}
Department of Computer
Science and Engineering
Thanks!…
Any question?