Operator Overloading in C M M
Operator Overloading in C M M
C++
C++ Classes and Objects
C++ Polymorphism
C++ Inheritance
C++ Abstraction
C++ Encapsulation
C++ OOPs Interview Questions
C++ OOPs MCQ
C++ Interview Questions
C++ Function Overloading
C++ Programs
C++ Preprocessor
C++ Templates
▲
Open In App
Related Articles
Solve Coding Problems
C++ Programming Language
C++ Overview
C++ Basics
C++ Variables and Constants
C++ Data Types and Literals
C++ Operators
C++ Input/Output
C++ Control Statements
C++ Functions
C++ Pointers and References
C++ Arrays
C++ Strings
C++ Structures and Unions
C++ Dynamic Memory Management
C++ Object-Oriented Programming
C++ Encapsulation and Abstraction
C++ Polymorphism
C++ Function Overloading
C++ Operator Overloading
o Operator Overloading in C++
o Types of Operator Overloading in C++
o Functors in C++
o What are the Operators that Can be and Cannot be Overloaded in C+
+?
C++ Inheritance
C++ Virtual Functions
C++ Exception Handling
C++ Files and Streams
C++ Templates
C++ Standard Template Library (STL)
C++ Preprocessors
C++ Namespace
Advanced C++
C vs C++
C++ vs Java
Competitive Programming in C++
C++ Interview Questions
Courses
in C++, Operator overloading is a compile-time polymorphism. It is an
idea of giving special meaning to an existing operator in C++ without
changing its original meaning.
In this article, we will further discuss about operator overloading in C+
+ with examples and see which operators we can or cannot overload in
C++.
C++ Operator Overloading
C++ has the ability to provide the operators with a special meaning for
a data type, this ability is known as operator overloading. Operator
overloading is a compile-time polymorphism. For example, we can
overload an operator ‘+’ in a class like String so that we can
concatenate two strings by just using +. Other example classes where
arithmetic operators may be overloaded are Complex Numbers,
Fractional Numbers, Big integers, etc.
Example:
int a;
float b,sum;
sum = a + b;
Here, variables “a” and “b” are of types “int” and “float”, which are
built-in data types. Hence the addition operator ‘+’ can easily add the
contents of “a” and “b”. This is because the addition operator “+” is
predefined to add variables of built-in data type only.
Implementation:
C++
// Overloading
class A {
statements;
};
int main()
a3 = a1 + a2;
return 0;
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-defined type i.e. of type “class A” using the “+” operator. This is
not allowed, because the addition operator “+” is predefined to
operate only on built-in data types. But here, “class A” is a user-
defined type, so the compiler generates an error. This is where the
concept of “Operator overloading” comes in.
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 meaning;
instead, they have been given additional meaning along with their
existing ones.
Example of Operator Overloading in C++
C++
// Operator Overloading
#include <iostream>
class Complex {
private:
public:
Complex(int r = 0, int i = 0)
real = r;
imag = i;
// This is automatically
called when '+' is used with
Complex operator+(Complex
const& obj)
Complex res;
res.real = real +
obj.real;
res.imag = imag +
obj.imag;
return res;
};
int main()
Complex c3 = c1 + c2;
c3.print();
Output
12 + i9
Difference between Operator Functions and Normal Functions
Operator functions are the same as normal functions. The only
differences are, that the name of an operator function is always
the operator keyword followed by the symbol of the operator, and
operator functions are called when the corresponding operator is
used.
Example
C++
#include <iostream>
class Complex {
private:
public:
Complex(int r = 0, int i = 0)
real = r;
imag = i;
Compl
ex const& c2);
};
return Complex(c1.real +
c2.real, c1.imag + c2.imag);
int main()
Complex c3
= c1
c3.print();
return 0;
Output
12 + i9
Can We Overload All Operators?
Almost all operators can be overloaded except a few. Following is the
list of operators that cannot be overloaded.
sizeof
typeid
Scope resolution (::)
Class member access operators (.(dot), .* (pointer to member
operator))
Ternary or conditional (?:)
Operators that can be Overloaded in C++
We can overload
Unary operators
Binary operators
Special operators ( [ ], (), etc)
But, among them, there are some operators that cannot be
overloaded. They are
Scope resolution operator (:
Member selection operator
Member selection through *
Pointer to a member variable
Conditional operator (?
Sizeof operator sizeof()
Operators that can be
overloaded Examples
Binary Arithmetic +, -, *, /, %
De-referencing (->)
Subscript []
Function call ()
Logical &, | |, !
#include <iostream>
class ComplexNumber {
private:
int real;
int imaginary;
public:
this->real = real;
this->imaginary =
imaginary;
ComplexNumber operator+
(ComplexNumber c2)
c3.real = this->real +
c2.real;
c3.imaginary = this-
>imaginary + c2.imaginary;
return c3;
};
int main()
ComplexNumber c3 = c1 + c2;
c3.print();
return 0;
Output
5 + i9
Explanation:
The statement ComplexNumber c3 = c1 + c2; is internally translated
as ComplexNumber c3 = c1.operator+ (c2); in order to invoke the
operator function. The argument c1 is implicitly passed using
the ‘.’ operator. The next statement also makes use of the dot
operator to access the member function print and pass c3 as an
argument.
Besides, these operators also work on names and not values and there
is no provision (syntactically) to overload them.
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 value of the conditional expression.
conditional statement ? 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.
Important Points about Operator Overloading
1) For operator overloading to work, at least one of the operands must
be a user-defined class object.
2) Assignment Operator: Compiler automatically creates a default
assignment operator with every class. The default assignment operator
does assign all members of the right side to the left side and works fine
in most cases (this behavior is the same as the copy constructor).
See this for more details.
3) Conversion Operator: We can also write conversion operators
that can be used to convert one type to another type.
Example:
C++
// of conversion operator
#include <iostream>
class Fraction {
private:
public:
Fraction(int n, int d)
num = n;
den = d;
{
return float(num) /
float(den);
};
int main()
float val = f;
return 0;
Output
0.4
Overloaded conversion operators must be a member method. Other
operators can either be the member method or the global method.
4) Any constructor that can be called with a single argument works as
a conversion constructor, which means it can also be used for implicit
conversion to the class being constructed.
Example:
C++
#include <iostream>
private:
int x, y;
public:
Point(int i = 0, int j = 0)
x = i;
y = j;
void print()
};
int main()
t.print();
t = 30; // Member x of t
becomes 30
t.print();
return 0;
Output
x = 20, y = 20
x = 30, y = 0