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

Unit-5 Operator Overloading

Uploaded by

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

Unit-5 Operator Overloading

Uploaded by

mavizkhanx28
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Unit-5: Operator Overloading

 Operator Overloading: Definition


 Unary Operator Overloading,
 Binary Operator overloading,
 Rules for Operators Overloading.
 Operators overloading using friend function.

Definition

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.

C++ provides a special function to change the current functionality of some operators within
its class which is often called as operator overloading. Operator Overloading is the method
by which we can change some specific operators‟ functions to do different tasks.
Syntax:

Return_Type classname :: operator op(Argument list)


{
Function Body
} // This can be done by declaring the function

Here,
 Return_Type is the value type to be returned to another object.
 operator op is the function where the operator is a keyword.
 op is the operator to be overloaded.

Operations that can be performed:

 Arithmetic operations: + – * / %
 Logical operations: && and ||
 Relational operations: == != >= <=
 Pointer operators: & and *
 Memory management operator: new, delete []

Why we use 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++ Program to Demonstrate the working/Logic behind Operator Overloading


class A {
statements;
};
int main()
{
A a1, a2, a3;
a3 = a1 + a2;
return 0;}

In above 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++ Program to Demonstrate


// Operator Overloading
#include <iostream>
using namespace std;
class Complex
{
private:
int real, imag;

Public:
Complex (int r = 0, int i = 0)
{
real = r;
imag = i;
}

// This is automatically called when '+' is used with


// 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'; }
};

int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2;
c3.print();
}

Unary Operator Overloading

consider overloading (-) unary operator. In the unary operator function, no arguments
should be passed. It works only with one class object. It is the overloading of an operator
operating on a single operand.
Key point
 No Arguments: Unary operator functions do not take any arguments.
 Member Function: Unary operators are typically implemented as member functions.
 Return Type: The return type can be void or any other type, depending on the
operation.
Example: Assume that class Distance takes two member objects i.e. feet and inches, and
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).

C++ program to show unary operator overloading

#include <iostream>
using namespace std;
class Distance
{
public:
int feet, inch; // Constructor to initialize the object's value
Distance(int f, int i)
{
this->feet = f;
this->inch = i;
}

// Overloading(-) operator to perform decrement operation of Distance object


void operator-()
{
feet--;
inch--;
cout << "\nFeet & Inches(Decrement): " << feet << "'" << inch;
}
};
int main()
{
Distance d1(8, 9);
-d1; // Use (-) unary operator by single operand
return 0;
}
In this example, the unary minus operator is overloaded to decrement the feet and inch values of
a Distance object by 1.

Binary Operator overloading

Binary operator overloading in C++ involves writing a function that redefines a binary operator
for user-defined types. This process allows objects of a class to interact using traditional operators like
+, -, *, etc. To overload a binary operator, you must specify the operator keyword followed by the
operator you intend to overload.
In the binary operator overloading function, there should be one argument to be passed. It is
the overloading of an operator operating on two operands. Below is the C++ program to show the
overloading of the binary operator (+) using a class Distance with two distant objects.

// C++ program to show binary operator overloading


include <iostream>
using namespace std;
class Distance
{
public:
int feet, inch;
Distance()
{
this->feet = 0;
this->inch = 0;
}
Distance(int f, int i)
{
this->feet = f;
this->inch = i;
}
//Overloading (+) operator to perform addition of two distance object Call by reference
Distance operator+(Distance& d2)
{
Distance d3; // Create an object to return
d3.feet = this->feet + d2.feet;
d3.inch = this->inch + d2.inch; // Return the resulting object
return d3;
}
};
int main()
{
Distance d1(8, 9);
Distance d2(10, 2);
Distance d3; //Use overloaded operator
d3 = d1 + d2;
cout << "\nTotal Feet & Inches: " << d3.feet << "'" << d3.inch;
return 0;
}

Rules for Operators Overloading

In C++, the rules of Operator overloading in c++ include:

1. Overloaded operators must have at least one operand that is a user-defined type.
2. Overloaded operators cannot change the precedence and associativity of operators.
3. Certain operators cannot be overloaded. (dot), .* (pointer to member), :: (scope
resolution), ?: (ternary conditional), and sizeof.
4. The arity of the Operator cannot be changed; for instance, you cannot make + unary if
it‟s binary.
5. Overloaded operators maintain their original meaning for built-in types.
6. Some operators are not suitable for overloading. For example, &&, ||, ,, . (member
selection), .* (member selection through a pointer), and:: (scope resolution).
7. The overloaded operators can be member functions or global functions.
8. Unary operators have one operand, binary operators have two, and ternary operators
have three.

Which operators Cannot be overloaded?

1. Conditional [?:], size of, scope(::), Member selector(.), member pointer selector(.*) and
the casting operators.
2. We can only overload the operators that exist and cannot create new operators or
rename existing operators.
3. At least one of the operands in overloaded operators must be user-defined, which
means we cannot overload the minus operator to work with one integer and one
double. However, you could overload the minus operator to work with an integer and a
mystring.
4. It is not possible to change the number of operands of an operator supports.
5. All operators keep their default precedence and associations (what they use for), which
cannot be changed.
6. Only built-in operators can be overloaded.

Advantages of an operator overloading in C++

1. Simplified Syntax: Operator overloading allows programmers to use notation closer to


the target domain, making code more intuitive and expressive.
2. Consistency: It provides similar support to built-in types for user-defined types,
enhancing consistency and ease of use.
3. Easier Understanding: Operator overloading can make programs more accessible to
understand by allowing the use of familiar operators with user-defined types, which can
improve code readability and maintainability.

Disadvantages of an operator overloading in C++

1. Potential Misuse: With great power comes great responsibility. Overloading operators
can lead to abuse or misuse, resulting in difficult-to-understand or maintain code.
2. Complexity: Overuse or misuse of operator overloading can introduce complexity,
especially when overloaded operators don‟t behave as expected or when there‟s
ambiguity in their usage.
3. Limited Overloading: While many C++ operations can be overloaded, there are some
exceptions, such as the member access operators (. and ->) and the scope resolution
operator (::). This limitation can sometimes restrict the flexibility of operator overloading
Example to Understand Operator Overloading in C++ Using Friend Function

#include <iostream>
using namespace std;
class Complex
{
private:
int real;
int img;
public:
Complex (int r = 0, int i = 0)
{
real = r;
img = i;
}
void Display ()
{
cout << real << "+i" << img;
}
friend Complex operator + (Complex c1, Complex c2);
};
Complex operator + (Complex c1, Complex c2)
{
Complex temp;
temp.real = c1.real + c2.real;
temp.img = c1.img + c2.img;
return temp;
}
int main ()
{
Complex C1(5, 3), C2(10, 5), C3;
C1.Display();
cout << " + ";
C2.Display();
cout << " = ";
C3 = C1 + C2;
C3.Display();
}
EXERCISE

1. Identify and write the program by using following output.

Input two complex numbers:


5
7
Input two complex numbers:
3
5
Entered values are:
5 + 7i
3 + 5i
The addition of two complex (real and imaginary) numbers: 8 + 12i
The subtraction of two complex (real and imaginary) numbers: 2 - 2i

2. Demonstrate by using binary (+) operator to perform the addition of two numbers.
3. Write and implement the code for following output.

You might also like