0% found this document useful (0 votes)
6 views

Introduction To Operator Overloading Final

Uploaded by

Putta Swamy
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Introduction To Operator Overloading Final

Uploaded by

Putta Swamy
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Chapter- 7

Operator Overloading in C++


Topics covered:
7.1 Operator Overloading
7.1.1 What is Operator Overloading?
7.1.2 How it is useful feature of C++ language?
7.2 Approaches to achieve operator overloading
7.2.1 Through member function
7.2.2 Through non-member function (Friend function)
7.2.3 Syntax of operator overloading through member function
7.2.4 Syntax of operator overloading through non-member (friend)
function
7.3 Rules for operator overloading
7.4 Compiler interpretation of operator overloading functions
7.5 Types of operator overloading (overloading various operators)
7.5.1 Unary operator overloading
7.5.2 Binary operator overloading
7.5.3 Overloading increment and decrement operator
7.5.4 Overloading unary minus and unary plus operator
7.5.5 Overloading arithmetic operators
7.5.6 Overloading relational operators
7.5.7 Overloading assignment operator
7.5.8 Overloading insertion and extraction operators
7.5.9 Overloading new and delete operators
7.5.10 Overloading subscript operator
7.5.11 Overloading pointer-to-member (->) operator (smart
pointer)
What is Overloading?

PUTTASWAMY B S Assistsnt professor 1


Overloading is a one of the concepts in object-oriented
programming, referred as changing the meaning of an already
defined function or pre-existing operator according to user
requirements without affecting original meaning.
Types of Overloading:
Overloading is a compile time
polymorphism in object-oriented programming. There are two
ways of overloading. They are,
 Function Overloading
 Operator Overloading

Function Overloading:
Function Overloading is defined as the process of
having two or more function with the same name, but different in
parameters. It means, means the method name same, but the
type of parameter should be different.
In function overloading, the function is redefined by using either
different types of arguments or a different number of arguments
or different sequence of parameters. It is also known as "static"
or "early binding".
Function Overloading can be achieved through the following two
cases:

PUTTASWAMY B S Assistsnt professor 2


 The names of the functions and return types are the same but
differ in the type of arguments.
 The name of the functions and return types are the same, but
they differ in the number of arguments.
 The name of the functions and return types are the same, but
they differ in the sequence of arguments.
Example:
1. Functions have different parameter type
 sum(int a, int b)
 sum(double a, double b)
2. Functions have a different number of parameters
 sum(int a, int b)
 sum(int a, int b, int c)
3. Functions have a different sequence of parameters
 sum(int a, double b)
 sum(double a, int b)
The above three cases are valid cases of overloading. We can
have any number of functions, but remember that the parameter
list must be different. For example:
 int mul(int, int)
 double mul(int, int)
As the parameter list is the same, this is not allowed. Even though
their return types are different, it’s not valid.
Example1 without class:
#include <iostream>
using namespace std;

PUTTASWAMY B S Assistsnt professor 3


void SumNum(int A, int B);
void SumNum(int A, int B, int C);
void SumNum(int A, int B, int C, int D);
int main()
{
SumNum(1,2);
SumNum(1,2,3);
SumNum(1,2,3,4);
return 0;
}
void SumNum(int A, int B)
{
cout<< endl << "SUMNUM is : "<< A+B;
}
void SumNum(int A, int B, int C)
{
cout<< endl << "SUMNUM is : "<< A+B+C;
}
void SumNum(int A, int B, int C, int D)
{
cout<< endl << "SUMNUM is : "<< A+B+C+D;
}
Example 2 with class definition:
#include <iostream>
using namespace std;
class Addition

PUTTASWAMY B S Assistsnt professor 4


{
public:
int sum(int a,int b)
{
return a+b;
}
int sum(int a,int b, int c)
{
return a+b+c;
}
};
int main(void)
{
Addition obj;
cout<<obj.sum(20, 15)<<endl;
cout<<obj.sum(81, 100, 10);
return 0;
}
Example:
#include <iostream>
using namespace std;
class Temp
{
private:
int x = 10;
double x1 = 10.1;

PUTTASWAMY B S Assistsnt professor 5


public:
void add(int y)
{
cout << "Value of x + y is: " << x + y << endl;
}
// Differ in the type of argument.
void add(double d)
{
cout << "Value of x1 + d is: " << x1 + d << endl;
}
// Differ in the number of arguments.
void add(int y, int z)
{
cout << "Value of x + y + z is: " << x + y + z << endl;
}
};
int main()
{
Temp t1;
t1.add(10);
t1.add(11.1);
t1.add(12,13);
return 0;}
Explanation:
 In the above example, the add function is overloaded.

PUTTASWAMY B S Assistsnt professor 6


 t1 is the object of class Temp, t1.add(10). It will call
void add(int y).
 t1.add(11.1), it will call void add(double d).
 t1.add(12,13), it will call void add(int y, int z).
 The overloaded functions are called by matching the type and
number of arguments. Because this information is available at
compile-time, the compiler selects the proper function based
on its parameters.
What is Operator Overloading?
An Operator Overloading is a mechanism (or concept) that
used to redefine or customize the behavior (functionality)
or meaning of certain operators, when they are used with
user defined data types (class or structs), without affecting
original meaning. It means, C++ allow us to specify more than
one definition (assigning additional functionality and behaviour)
to pre-existing operator in the same scope (beyond their built-in
functionality).
For example, we use “+" operator used to perform addition on
integers, concatenation on strings, and addition on complex
numbers. This enhances the flexibility of operators, allowing them
to operate on a wider range of data types.
For Example:
float a;
int b, sum;
sum = a+b;

PUTTASWAMY B S Assistsnt professor 7


In the above example we can see that a is float data type variable
whereas b and sum are integer data type variables so, the line
sum = a+b will not create any problem as both the data types i.e.
float and sum are predefined so there will be no objection as the
+ operator knows what to do with the pre-defined data types.
However, in the below example,
class E
{
};
int main() {
E e1,e2,e3;
e3= e1 + e2;
return 0;
}
We have created a class with the name E and in the main function
we are creating an object with the name e1, e2, e3 and
performing e3=e1+e2 using + operator. This line will give an
error because, do not know what to do with objects of a user-
defined class. Here we are not performing operations on
predefined data types we are performing operations on user-
defined classes and objects. In these types of scenarios operator
overloading comes into play.

PUTTASWAMY B S Assistsnt professor 8


Different approaches of Operator Overloading:
To overload the operators in C++, you need to define a
function called as operator function that implements the desired
behavior (change the meaning) of the pre-defined operator. The
function should have a specific name and signature based on the
operator being overloaded. There are three ways to write
(implement) the operator function. They are,
1. Operator function as Member Function
2. Operator function as Non-Member Function
3. Operator function as Non-Member Function (Friend Function)
Friend function used to access the private and protected class
members. Both operands are passed as arguments, and neither
operand is implied as the calling object.
General Syntax to overload the operator through member
function:
To overload operator, implement overload function (operator
function) as member functions (By adding the operator function
as a class member function):

PUTTASWAMY B S Assistsnt professor 9


Inside a class with parameter:
Class_name operator<operator_symbol>(const Class_name& obj)
(return_type operator operator_symbol ([parameters]) )
{
// Define the behavior of the operator
// You can access the current object using 'this' pointer
}
Inside a class without parameter
return-type operator operatorsymbol( )
{
//body of the function
}
Outside a class:

PUTTASWAMY B S Assistsnt professor 10


General syntax to overload the operator through friend
function:
To overload operator, implement overload function
(operator function) as friend function (The global friend function
created for the operator function). This method of operator
overloading is referred to as a non-member function inside a
class. It has permission to access both types of members,
including private and protected members.
 friend return_type operator op(parameters);
 friend ClassName operator<operatorSymbol>(const ClassName&
obj1); unary operator
 friend ClassName operator<operatorSymbol>(const ClassName&
obj1, const ClassName& obj2); Binary operator
Here,
 The class keyword marks beginning of class definition with
the name className, and public is an access specifier that
controls the level of visibility for class elements.
 Return-type: indicates the type of value returned by the
member function. If function returns anything, then keyword
‘void’ is used.
 The operator keyword indicates that we are overloading an
operator, and the symbol refers to the sign/ symbol of the
respective operator we want to overload (i.e., +, <, -, ++,
etc.).
 The parameter_list - indicates the arguments that are passed
to the function. When this operator function is called, the

PUTTASWAMY B S Assistsnt professor 11


operations are performed on those arguments that are passed
to the function.
 The function is declared a 'friend' of the class with this syntax,
enabling it to access its private members. The remaining
portions of the grammar resemble member function
overloading.
Note-1: If the operator is overload through friend function, then it
will have one argument for unary operator and two arguments
for binary operator.
Note-2: If the operator overload through member function, then
it will have no arguments for unary operators and one argument
for binary operators.
Note-3: The operator overloading function may be a member
function, the left operand is an object for which the operator is
called of the Class, and the right-hand operand is passed as an
argument. Whereas, when the Left operand is different, the
Operator overloading function should be a non-member function.
Note-4: You can make the operator overloading function has
friend function, both operands are passed as arguments, and
neither operand is implied as the calling object.
Overloadable and Non-overloadable Operators:
Most operators in C++ can be overloaded except for a few.
Following is the list of operators that can be overloaded:
Overloadable Operators Symbols

Unary Arithmetic Operators +, -, ++, —, !

Binary Arithmetic Operators +, -, *, /, %


PUTTASWAMY B S Assistsnt professor 12
Assignment Operator & Compound =, +=,*=, /=,-=,

Assignment Operators %=

Logical Operators &, ||

Relational Operators >, < , = =, <=,

>=

Bitwise Operators (Input and Output & , | , << , >> ,

stream operator) ~,^

De-referencing Operator/ Member Access ->, .,*

Operator

Subscript Operator []

Dynamic memory allocation and De- new(), delete()

allocation Operators

Function call ()

The operators that cannot be overloaded are given below:


Non-Overloadable Operators Symbols
Scope Resolution Operator ::
Ternary/ Conditional Operator (?:)
Class Member Selector Operator (.)
Sizeof Operator (object size sizeof()
information)
Member selection with Pointer-to- (.*)
PUTTASWAMY B S Assistsnt professor 13
member Operator
Object type Operator (object type (typeid)
information)
Casting operator Static_cast
Const_cast
Reinterpret
_cast
Dynamic_ca
st
Among the in-built operators which operators cannot be
overloaded using the friend function but can be overloaded
by member functions are as follows:
 Assignment Operator (=)
 Function call Operator (())
 Subscript Operator ([])
 Arrow Operator (->)
Above overloadable operators are classified into two categories.
They are,
1. Binary operators
2. Unary operators
Rules for operator overloading:
When overloading operators, it is essential to
follow certain rules to ensure proper usage and maintain
consistency. Here are some key rules to keep in mind:

PUTTASWAMY B S Assistsnt professor 14


 Only existing member (built-in operators) can be overloaded.
We can’t create our own operator to overload (new operators
cannot be overloaded).
 Operators cannot be overloaded for built in types only. It
means, overloaded operator must have (contains) at least one
operand must be user-defined type.
 Overloaded operators follow the syntax rules of original
operators. This means we can’t change the basic meaning of
an operator (it means retain their original meaning for built-in
types).
 Precedence and associativity of operators cannot be changed
through overloading.
 Overloaded operators cannot have default arguments except
the function call operator () which can have default arguments.
 Overloaded operators cannot alter the number of operands.
 Some operators can’t be overloaded. They are: &&, ||, member
access(selection) operator (.), member selection through a
pointer (.*), scope resolution operator (::), size operator
(sizeof), ternary operator (? :).
 Binary arithmetic operators such as +, -, *, / must explicitly
return a value.
 We can’t use friend function to overload some operators. They
are assignment operator (=), function call operator (()),
subscripting operator ([]), class member access operator (->).
However, the member function can be used to overload those
operators.

PUTTASWAMY B S Assistsnt professor 15


 Except the operators specified in above, all other operators can
be either member functions or a non-member functions.
 If the operator is overload through friend function, then it will
have one argument for unary operator and two arguments for
binary operator. If the operator overload through non-static
member function, then it will have no arguments for unary
operators and one argument for binary operators.
 When binary operators are overloaded through member
function, the left-hand operand must be an object of the
relevant class.
 Some operators like (assignment)=, (address)& and comma (,)
are by default overloaded.
Binary Operator:
A binary operator is an operator in
programming and mathematics that works (acts) on two
operands to perform a specific operation. The term "binary"
indicates that these operators specifically take two operands.
These operands can be variables, constants, or expressions.
Binary operators are commonly used in arithmetic, logical,
bitwise, and relational operations.
1. Arithmetic Operators: perform computation
 Addition (+): Adds two operands.
 Subtraction (-): Subtracts the second operand from the first.
 Multiplication (*): Multiplies two operands.
 Division (/): Divides the first operand by the second (result is
truncated if both operands are integers).

PUTTASWAMY B S Assistsnt professor 16


 Modulo (%): Computes the remainder of the division of the
first operand by the second.
2. Relational (Comparison) Operators: Used to compare two
values. They return a Boolean result (true or false).
 Equal to (==): Checks if two operands are equal.
 Not equal to (!=): Checks if two operands are not equal.
 Greater than (>): Checks if the first operand is greater.
 Less than (<): Checks if the first operand is smaller.
 Greater than or equal to (>=): Checks if the first operand is
greater or equal.
 Less than or equal to (<=): Checks if the first operand is
smaller or equal.
3. Logical Operators: Operate on boolean values and return a
boolean result.
 Logical AND (&&): Returns true if both operands are true.
 Logical OR (||): Returns true if at least one operand is true.
4. Bitwise Operators: Perform bit-level operations:
 AND (&): Performs a bitwise AND operation.
 OR (|): Performs a bitwise OR operation.
 XOR (^): Performs a bitwise XOR operation.
 Left Shift (<<): Shifts bits to the left.
 Right Shift (>>): Shifts bits to the right.
5. Assignment Operators: Assign values to variables:
 Simple Assignment (=): Assigns the value of the right
operand to the left operand.
 Compound Assignment:

PUTTASWAMY B S Assistsnt professor 17


o +=: Adds and assigns.
o -=: Subtracts and assigns.
o *=: Multiplies and assigns.
o /=: Divides and assigns.
o %=: Finds the remainder and assigns.
o &=, |=, ^=, <<=, >>=: Bitwise compound assignments.
Example: int a = 5; a += 3; // a = a + 3, so a = 8
6. Member Access Operators
 Dot (.): Accesses a member of a class or structure.
 Arrow (->): Accesses a member through a pointer.
Example:
struct Point {
int x, y;};
Point p = {10, 20};
cout << p.x; // Accessing x using the dot operator
7. Other Binary Operators
o Subscript Operator: [] (array subscript): Provides access to elements in
custom collections (like matrices or lists).
o () (Function call)
o -> (Member access through a pointer)

Step-by-step Procedure for overloading the operator in C+


+:
Overloading operators in C++ is a
powerful feature that allows you to redefine the behavior of
PUTTASWAMY B S Assistsnt professor 18
operators for user-defined types, such as classes. Here's a step-
by-step guide for overloading operators in C++:
Step 1: Understand Operator Overloading
 Operators like +, -, *, ==, ++, --, etc., can be overloaded.
 You cannot overload certain operators: ::, .*, ., sizeof, etc.
 Overloaded operators must either be a member function or a
non-member function (often a friend function).
Step 2: Choose an Operator to Overload
Decide the operator you want to overload, depending on the
behavior you need. For example:
Step 3: Decide the Overloading Type
 Member function: Used when the left-hand operand is always
an object of the class.
 Friend function: Used when the left-hand operand is not an
object of the class or needs access to private data.
Step 4: Define the Operator Function: The syntax for the
operator overloading function is:
Member Function
ReturnType ClassName::operatorSymbol(ArgumentType) {
// Define operator behavior
}
Friend Function
ReturnType operatorSymbol(const ClassName& obj1, const
ClassName& obj2)
{
// Define operator behavior }

PUTTASWAMY B S Assistsnt professor 19


Step 5: Implement the Operator Overloading – write a main
function
Step 6: Test the Code
 Create objects and test the overloaded operators.
 Check if the expected behavior is achieved.
Summary of Steps
1. Understand the operator's functionality and constraints.
2. Choose the type of overloading (member or friend function).
3. Define the operator function in the class.
4. Implement the functionality of the operator.
5. Test the overloaded operator with objects.
To write a C++ program illustrating Unary Operator
Overloading.
Step 1: Declare the class.
Step 2: Declare the variables a, b, c and d.
Step 3: Using the parameterized constructor as num(int p,int q,int
r,int s).
Step 4: Define the operator function ++ to increment the values
Step 5: Define the display function.
Step 6: Declare the class object as n1.
Step 7: Passing values through object to constructor.
Step 8: Call the function operator ++() by incrementing the class
object and call display().

Various types of operator overloading


Binary Operator Overloading

PUTTASWAMY B S Assistsnt professor 20


PUTTASWAMY B S Assistsnt professor 21

You might also like