Operator Overloading
Operator Overloading
By
Dr. Muhammad Nadeem Ashraf
Operator Overloading
• It is an idea of giving special meaning to an existing operator in C++
without changing its original meaning.
• Operators are predefined for certain data types like + (addition) for
numeric data, . (DOT) for objects etc.
• Operator overloading is a compile-time polymorphism.
• C++ facilitates programmers to define the behavior of well known
operators for user-defined types (classes) known as operator
overloading.
• Classes where arithmetic operators may be overloaded are Complex
Numbers, Fractional Numbers, Big integers, etc.
Operator Overloading
• Examples: Here, variables “a” and “b” are of types “int” and “float”, which are built-
in data types.
int a; Hence the addition operator ‘+’ can easily add the contents of “a” and
float b, sum; “b”.
sum = a + b; This is because the addition operator “+” is predefined to add variables of
built-in data type only.
by a simpler code:
i5 = (i1 + i2) / (i3 - i4)
Operator Overloading
// Example Program to Demonstrate the working/Logic behind Operator Overloading
class A {
//statements; In this example, we have 3 variables “a1”, “a2” and “a3” of type “class
}; A”.
Here we are trying to add two objects “a1” and “a2”, which are of user-
int main() defined type i.e. of type “class A” using the “+” operator.
{ This is Not allowed, because the addition operator “+” is predefined to
A a1, a2, a3; operate only on built-in data types.
But here, “class A” is a user-defined type, so the compiler generates an
a3 = a1 + a2; error. This is where the concept of “Operator overloading” comes in.
return 0; Now, if the user wants to make the operator “+” add two class objects,
} the user has to redefine the meaning of the “+” operator such that it adds
two class objects.
This is done by using the concept of “Operator overloading”.
So the main idea behind “Operator overloading” is to use C++ operators
with class variables or class objects.
Redefining the meaning of operators really does not change their original
Operator Overloading
• If we create a class Complex with behavior similar to complex
numbers (in mathematics domain), it would be more natural to
overload + operator enabling programmers to write statements like
mathematical expression making it a lot more readable.
• Which of the below expressions is more readable???
Sum.calculateSum(c1, c2); Sum = c1 + c2;
class Complex {
private:
int real, imag; int main()
{
public: Complex c1(10, 5), c2(2, 4);
Complex(int r = 0, int i = 0) Complex c3 = c1 + c2; Output:
{ c3.print(); 12 + i9
real = r; }
imag = i;
}
// This is automatically called when '+' is used between two Complex objects
Complex operator+(Complex const& obj)
{
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << '\n'; }
};
Member Operator Function … Syntax
return-type Class-Name::operator (arguments-list) {
// body goes here
}
One can see that the overloaded operator looks like a function with slight
differences of syntax
Format
• write function definition as normal
• function name is keyword operator followed by the symbol for the
operator being overloaded.
operator+ would be used to overload the addition operator (+).
Though mostly overloaded operators return object types but C++ allows
any valid type. For example, it is more natural when two Complex objects
are added using + overloaded-operator, to return an object of Complex
type
Member Operator Function … Syntax
Member Operator Function … Example
One can see that in loc class, overloading of + operator takes only one
loc object as parameter but when we use if main() it receives two
parameters ob1 and ob2.
The reason for this difference is that ob1 is an invoker for + operator
and it is passed to the overloaded member implicitly by compiler.
Operator Overloading
• The assignment operator (=) may be used with every class
without explicit overloading
• Member wise assignment
• The same is true for the address operator (&)
Overloading Binary Operator
Explanation:
1.Line: Distance operator+(Distance &d2): Here return type of function is
• In the
distance and itbinary
uses call by operator
references to overloading
pass an argument.function, there
should
2.Line: d3be= d1 one+ d2:argument
Here, d1 calls tothebeoperator
passed.
function of its class object and
takes d2 as a parameter, by which the operator function returns the object and the
• It iswillthe
result reflect overloading
in the d3 object.of an operator operating on two
// C++ program to show binary operator overloading Output:
operands.
#include <iostream>
Total Feet & Inches:
using namespace std; // Overloading (+) operator to perform addition of
two distance // object Call by reference 18'11
class Distance { Distance operator+(Distance& d2) // Driver Code
public: { int main()
int feet, inch; // Create an object to return {
Distance d3; Distance d1(8, 9);
Distance() Distance d2(10, 2);
{ Distance d3;
this->feet = 0; d3.feet = this->feet + d2.feet;
this->inch = 0; d3.inch = this->inch + d2.inch; // Use overloaded operator
} d3 = d1 + d2;
Distance(int f, int i) // Return the resulting object
{ return d3; cout << "\nTotal Feet & Inches: " << d3.feet <<
this->feet = f; } "'" << d3.inch;
this->inch = i; }; return 0;
}
Overloading Unary Operator
• Let us consider overloading (-) unary operator. In the unary
operator function, no 2nd arguments should be passed.
• It works only with one class object. It is the overloading of
an operator operating on a single operand.
• Example:
• Assume that class Distance has two member objects i.e.
feet and inches
• Creates a function by which the Distance object should
decrement the value of feet and inches by 1 (having a
single operand of Distance Type).
Overloading Unary Operator
// C++ program to show unary operator overloading
#include <iostream>
using namespace std;
// Driver Code
class Distance { int main()
public: {
int feet, inch; Distance d1(8, 9);
loc class
Member Operator Function … Task … Implementation
Create a location
class as used in
previous example.
Overload different
operators
including +, +=, -,
-=, = , -- and ++.
main() method to
test the
functionality of loc
class.
Member Operator Function … Task … Implementation
Create a location
class as used in
previous example.
Overload different
operators
including +, +=, -,
-=, = , -- and ++.
Constructors,
Setters and
show() method
implementation in
loc class
Member Operator Function … Task … Implementation
Create a location
class as used in
previous example.
Overload different
operators
including +, +=, -,
-=, = , -- and ++.
&
+ and +=
operators
overloading
implementation in Similar implementation for – and
loc class -= operators.
Member Operator Function … Task … Implementation
Create a location
class as used in
previous example.
&
Overload different
operators
including +, +=, -,
-=, = , -- and ++. &
++, -- and =
operators
overloading
implementation in
loc class
Restrictions on Operators Overloading
The precedence of an operator cannot be changed
The number of operands for an operator cannot be changed. One
might effectively reduce the operands by ignoring them.
Overloaded operators cannot have default arguments ... (the exception of
the operand that is a function call)
Few operators cannot be overloaded in C++
1. sizeof
2. typeid
3. Scope resolution (::)
4. Class member access operators (.(dot), .* (pointer to member operator))
5. Ternary or conditional (?:)
Why can’t the above-stated
operators be overloaded? // C++ program to demonstrate operator overloading using dot
operator
#include <iostream> int main()
using namespace std; {
Explanation:
1. sizeof Operator ComplexNumber c1(3,
The statement
This returns ComplexNumber
the size c3 =class
of the object or datatype c1 + c2;asisthe operand.
entered
ComplexNumber { This 5);
is evaluated by the compiler and
internally translated as ComplexNumber
cannot be evaluated during runtime. The proper c3
private: =
incrementing of a pointer in an arrayComplexNumber
of objects reliesc2(2,
on
the sizeof operator implicitly. Altering its meaning using
intoverloading 4);
would cause a fundamental part of the
c1.operator+ (c2); in order to invoke the operator real;
language to collapse. int imaginary; ComplexNumber c3 = c1
function. + c2;
2. typeid Operator
The argument c1 is implicitly passed public: using c3.print();
This provides a CPP program with the ability to recover the actually derived type of the object
return 0; referred to by
Output:
the ‘.’ operator. ComplexNumber(int real,
a pointer or reference. For this operator, the whole point is to uniquely identify int
a imaginary)
type. If we want to make 5a + i9
{ }
The next statement
user-defined alsoanother
type ‘look’ like makes usepolymorphism
type, of the dot can be used but the meaning of the typeid
operator must remain unaltered, or else serious issues this->real = real;
operator to access the member function print could
and arise.
this->imaginary = imaginary;
3. Scope
pass c3 asresolution (::) Operator
an argument. }
This helps identify and specify the context to
Besides, these operators also work on namesvoid which an identifier
andprint()refers
{ coutby
<<specifying
real << " a
+ namespace. It is }
i" << imaginary;
completely evaluated at runtime and works on names ComplexNumber
rather than values. The operands of scope c2)
operator+(ComplexNumber resolution
not values and there is no provision (syntactically)
are note expressions with data types and CPP has no syntax for capturing them if it were overloaded. So it is
{
to overloadimpossible
syntactically them. to overload this operator. ComplexNumber c3(0, 0);
4. Class member access operators (.(dot), .* (pointer to member operator))
c3.real = this->real + c2.real;
c3.imaginary
The importance and implicit use of class member access operators = this->imaginary
can be understood through+the following
example: c2.imaginary;
Example: return c3;
}
};
Why can’t the above-stated
operators be overloaded?
5. Ternary or conditional (?:) Operator
The ternary or conditional operator is a shorthand representation of an if-else
statement.
In the operator, the true/false expressions are only evaluated on the basis of the truth
conditional
value statementexpression.
of the conditional ? expression1 (if statement is TRUE) : expression2
(else)
A function overloading the ternary operator for a class say ABC using the definition
ABC operator ?: (bool condition, ABC trueExpr, ABC falseExpr);
would not be able to guarantee that only one of the expressions was evaluated. Thus,
the ternary operator cannot be overloaded.
Operator Overloading using Friend Functions
1. An operator can be overloaded using a non-member function,
which is usually a friend function
2. Since a friend function is a non-member for a class, it does not
have this pointer
3. Since a friend function does not have this pointer, the concept
of invoker object is not relevant here. So a friend function
defining two operands will have two parameters.
4. When a friend function is overloading a binary operator, the
very first parameter will be treated as the left operand of the
operator and the second parameter will be treated as the right
side operand.
5. Similarly, a unary operator overloaded with a friend function
will have one parameter.
Operator Overloading using Friend Functions
Syntax:
class class-name {
…
public:
friend return-type operator opr (parameter-list);
};
Operator Overloading using Friend Functions
Syntax:
class class-name {
…
public:
friend return-type operator opr (parameter-list);
};
Operator Overloading using Friend
Functions: Example
#include <iostream>
using namespace std;
class Complex { int main()
private: {
int real, imag; Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // An example call
public: to "operator+"
Complex(int r = 0, int i = 0) c3.print();
{ return 0;
real = r; }
imag = i;
}
void print() { cout << real << " + i" << imag << endl; } Output:
// The global operator function is made friend of this 12 + i9
// class so that it can access private members
friend Complex operator+(Complex const& c1, Complex
const& c2);
}; Both Two Objects (c1 and c2) are passed
Complex operator+(Complex const& c1, Complex const& c2)
{
in case of
return Complex(c1.real + c2.real, c1.imagoverladed
+ c2.imag);operator (+) using friend functions
}
Operator Overloading using Friend Functions
Code
Example
Restrictions on Friend Functions
1. =, (), [] and operators cannot be overloaded using friend
functions
2. When overloading the increment or decrement operators, one
will need to use a reference parameter when using a friend
function
Operator Overloading using Friend Functions
Code
Example
Overloading Unary Operators