0% found this document useful (0 votes)
3 views15 pages

OOPS Unit 3 Operator Overloading

Uploaded by

sai.dontreachout
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views15 pages

OOPS Unit 3 Operator Overloading

Uploaded by

sai.dontreachout
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Operator Overloading in C++ With Examples

What is Operator overloading in C++?

c++ operator overloading refers to the practice of redefining the functionality of operators for user-
defined data types.

This feature, also known as “operator overriding in C++,” allows you to customize the behavior of
operators such as +, -, *, and / to work with objects of your classes, enhancing the flexibility and
expressiveness of your code.

What are Operators?

Operators in programming languages are symbols or keywords that perform specific operations on
operands to produce results.

These operations can include arithmetic operations like addition and subtraction, comparison
operations like equal to and not equal to, logical operations like AND and OR, and more. In essence,
operators enable you to manipulate data and control the flow of your code.

Also, Explore beginner-friendly Simple C++ Programs to learn the C++ fundamentals.

What are the types of operator overloading?

There are two types of operator overloading:

 Function overloading.

 Operator overloading.

What is function overloading?

The process of having two or more functions with the same name but with different parameters
(arguments) is called function overloading. The function is redefined by either using different types
of arguments or a different number of arguments. It is only through these differences that a compiler
can differentiate between functions.

What is Operator overloading?

Operator overloading in C++ program can add special features to the functionality and behavior of
already existing operators, such as mathematics and other operations.

The mechanism of giving special meaning to an operator is known as operator overloading. For
example, we can overload an operator ‘+’ in a class-like string to concatenate two strings by just
using +.

Operations that can be performed:

 Arithmetic operations: + – * / %

 Logical operations: && and ||

 Relational operations: == != >= <=

 Pointer operators: & and *

 Memory management operator: new, delete []

Implementing Operator Overloading Examples

Example 1: Let us multiply two fractions using the overloading of the multiplication operator in C++.

1 // Multiplication of two fractions

2 #include <iostream>

3 using namespace std;

5 class Frac {

6 private:

7 int a;

8 int b;

10 public:

11 Frac() : a(0), b(0) {}

12

13 void in() {

14 cout << "Enter the numerator : ";


15 cin >> a;

16 cout<< "Enter the denominator : ";

17 cin >> b;

18 }

19

20 // Overload the * operator

21 Frac operator * (const Frac &obj) {

22 Frac temp;

23 temp.a = a * obj.a;

24 temp.b = b * obj.b;

25

26 return temp;

27 }

28

29 void out() {

30 cout<<"The fraction is "<< a<<"/ "<<b;

31 }

32 };

33

34 int main() {

35 Frac F1, F2, result;

36

37 cout << "Enter the first fraction:n";

38 [Link]();

39

40 cout << "Enter the second fraction:n";

41 [Link]();

42

43 // complex1 calls the operator function

44 // complex2 is passed as an argument to the function

45 result = F1 * F2;
46 [Link]();

47

48 return 0;

49 }

1 OutPut

2 Enter the first fraction:

3 Enter the numerator : 2

4 Enter the denominator : 5

5 Enter the second fraction:

6 ENter the numerator: 12

7 Enter the denominator: 7

8 The fraction is 24/35

Explanation
This code demonstrates Operator overloading in C++ to multiply two fractions. The Frac class defines
a fraction with numerator a and denominator b and overloads the * operator to perform the
multiplication of fractions.

When executed, the program prompts the user to input two fractions, multiplies them using the
overloaded * operator, and prints the result. In the provided output, when the
fractions 2/5 and 12/7 are multiplied, the result is correctly calculated as 24/35.

Example 2: A C++ program to overload a prefix decrement operator

1 #include <iostrea

3 }

5 // Overload the prefix decrement operator

6 void operator-- () {

7 a= --a;

8 b= --b;

9 }

10

11 void out() {

12 cout<<"The decremented elements of the object are: "<<endl<< a<<" and " <<b;
13 }

14 };

15

16 int main() {

17 OverLoad obj;

18 [Link]();

19 --obj;

20 [Link]();

21

22 return 0;

23 }

1 Output

2 Enter the first number : 56

3 Enter the second number : 234

4 The decremented elements for the objects are: 55 and 223

Explanation
This code showcases the overloading of the prefix decrement operator in C++. The OverLoad class
represents two integer variables, a and b, and overloads the — operator to decrement both.

Upon execution, the program prompts the user to input two numbers, then decrements them using
the overloaded — Operator and displays the decremented values. In the provided
output, 56 and 234 are decremented to 55 and 223 respectively.

Example 3: Overloading a NOT (!) operator

1 #include <iostream>

2 using namespace std;

4 class NotOp {

5 private:

6 int a;

7 bool b;

9 public:

10 NotOp() : a(0), b(true) {}


11

12 void in() {

13 cout << "Enter the first number : ";

14 cin >> a;

15 cout<< "Enter true or false : ";

16 cin >> b;

17 }

18

19 // Overloading the NOT (!) operator

20 void operator ! () {

21 a= !a;

22 b= !b;

23 }

24

25 void out() {

26 cout<<"Output: "<<endl<< a<<endl<<b;

27 }

28 };

29

30 int main() {

31 NotOp obj;

32 !obj;

33 [Link]();

34

35 return 0;

36 }

1 Output

2 1

3 0

Explanation
This code demonstrates the overloading of the NOT (!) Operator in C++. The NotOp class includes an
integer variable, a, and a boolean variable, b. It overloads the! The Operator will perform logical
negation on both variables.

Upon execution, the program prompts the user to input a number and a boolean value, then applies
the overloaded ! Operator and displays the negated values. In the provided output, the number is
negated to 1 (if initially non-zero), and the boolean value is negated to 0.

What are the rules for operator overloading in C++?

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.

What are Unary Operators and Binary Operator overloading?

Unary Operators Overloading

Unary operator overloading involves defining behaviors for operators that act on a single operand.
For example, increment (++), decrement (—), logical NOT (!), and unary minus (–) are unary
operators that can be overloaded in C++. This means you can redefine their behavior for your custom
classes.

Example: Let us try overloading the increment and decrement operators through a C++ program.

1 #include<iostream>

2 using namespace std;

4 class UnaryOverload

5 {

6 int hr, min;

7 public:

8 void in()

9 {

10 cout<<"n Enter the time: n";

11 cin>>hr;

12 cout<<endl;

13 cin>>min;

14 }

15 void operator++(int) //Overload Unary Increment


16 {

17 hr++;

18 min++;

19 }

20 void operator--(int) //Overload Unary Decrement

21 {

22 hr--;

23 min--;

24 }

25

26 void out()

27 {

28 cout<<"nTime is "<<hr<<"hr "<<min<<"min";

29

30 }

31 };

32 int main()

33 {

34 UnaryOverload ob;

35 [Link]();

36 ob++;

37 cout<<"nn After Incrementing : ";

38 [Link]();

39 ob--;

40 ob--;

41 cout<<"nn After Decrementing : ";

42 [Link]();

43 return 0;

44 }

1 Output

2 Enter the time:


3 5

4 56

5 After Incrementing:

6 Time is 6hr 57 mins

7 After Decrementing:

8 Time is 4hr 55 min

Explanation
This code illustrates unary Operator overloading in C++. The UnaryOverload class represents time in
hours and minutes. It overloads the unary increment (++) and decrement (–) operators to increment
and decrement the time, respectively.

Upon execution, the program prompts the user to input the time, then increments it and displays the
result. Subsequently, it decrements the time twice and shows the final result. In the provided output,
the time is incremented from 5hr 56min to 6hr 57min and then decremented to 4hr 55min as
expected.

Binary Operator Overloading

Binary Operator overloading defines behaviors for operators that act on two operands.

Common binary operators include addition (+), subtraction (-), multiplication (*), division (/), and
comparison operators like equal to (==) and less than (<). By overloading these operators, you can
specify how they should operate on objects of your custom classes, allowing for intuitive and natural
expressions in your code.

Example: Let us see the following C++ code that elaborates the overloading of the addition operator.

1 #include <iostream>

2 using namespace std;

4 class Time {

5 private:

6 int hour;

7 int minute;

9 public:

10 Time() : hour(0), minute(0) {}

11
12 void in() {

13 cout << "Enter the time: ";

14 cin >> hour;

15 cin >> minute;

16 }

17

18 // Overload the + operator

19 Time operator + (const Time & obj) {

20 Time temp;

21 [Link] = hour + [Link];

22 [Link] = minute + [Link];

23 if ([Link]>=60)

24 {

25 [Link]+=1;

26 [Link]-=60;

27 }

28 if ([Link]>24)

29 [Link]=1;

30 return temp;

31 }

32

33 void out() {

34 cout<<"Time is "<< hour<<"hrs "<<minute<<"min";

35 }

36 };

37

38 int main() {

39 Time T1, T2, result;

40

41 cout << "Enter first time in hours and minutes one by one :n";

42 [Link]();
43

44 cout << "Enter second time in hours and minutes one by one :n";

45 [Link]();

46

47 // T1 calls the operator function

48 // T2 is passed as an argument to the function

49 result = T1 + T2;

50 [Link]();

51

52 return 0;

53 }

1 Output

2 Enter first time in hours and minutes one by one:

3 Enter the time:11

4 56

5 Enter second time in hours and minutes one by one:

6 Enter the time: 2

7 10

8 Time is 14hrs 6 min

Explanation
This code demonstrates binary Operator overloading in C++. The Time class represents time in hours
and minutes. The + Operator is overloaded to add two Time objects together.

Upon execution, the program prompts the user to input two times, adds them using the overloaded
+ Operator, and displays the result. In the provided output, 11hrs 56min and 2hrs 10min are added
together, resulting in 14hrs 6min.

Overloadable/Non-overloadable Operators

Now that you saw the overloading of unary and binary operators in C++ in the previous sections of
this blog, you must know that not all operators can be overloaded. The operators that can be
overloaded in C++ are known as overloadable operators. However, there are some non-overloadable
operators as well that can’t be overloaded.

The list of non-overloadable operators goes as follows:

 Ternary operator
 Dot operator or member access operator (.)

 Pointer to member operator (.*)

 Scope resolution operator ( :: )

 Object type operator (typeid)

 Object size operator (sizeof)

These operators cannot be overloaded because doing so will cause significant programming
problems. As an illustration, the sizeof operator returns the operand, which is the size of the object
or datatype. The compiler evaluates this. It cannot be assessed in real-time. We can’t thus
overburden it.

Overloading special operators in C++

Some of the special operators in C++ are as follows:

1. new – It is used to allocate the memory dynamically.

2. Delete – It is used to free the memory dynamically.

3. [] – It is a subscript operator.

4. -> – – It is a member access operators.

5. = – It is used to assign the values.

6. () – It is used for function call.

The operators other than listed above can be overloaded either as a member or as non-members.
But in general, non-member overloading is recommended. Because:

1. Symmetry: When a binary operator is defined as a class method, it must have objects as its
operands. We should write like complex*5 but not like 5*complex because 5.
operator*(complex)does not make any sense. In other words, a*b should be the same as
b*a. Otherwise, it breaks the cumulativeness that the user is expecting from the *operator.
So, in this case, we should use no-member operators overloading.

2. Weak coupling: since a non-member method cannot access private member, it tends to
make the class less coupled

Example:

1 Using unary operator:

2 //Overload ++ when used as prefix

3 #include<iostream.h>

4 Using namespace std;

5 Class count

6 {

7 Private:
8 Int value;

9 Public:

10 //constructor to initialize count to 5

11 Count() : value(5) {}

12 //overload ++ when used as prefix

13 Void operator ++ ()

14 {

15 ++value;

16 }

17 Void display()

18 {

19 Cout<<”Count: “<<value<<endl;

20 }

21 };

22 Int main()

23 {

24 Count count1;

25 //call the “void operator ++ ()” function

26 ++count1:

27 [Link]();

28 Return 0;

29 }

1 Output

2 Count: 6

Explanation
In this code, when we write ++count1, the void operator++() function is triggered. This function
increments the value attribute of the count1 object by 1. Operator overloading allows us to redefine
how operators behave.

For instance, we could have made ++ increase the value by 100, but clarity is crucial in coding.
Consistently and using overloaded operators ensures easy comprehension.

In this example, ++ is overloaded as a prefix. The syntax void operator++() is used, with int inside
parentheses to indicate it’s a unary operator. This clarifies the usage, avoiding confusion.

You might also like