Operator Overloading in C++

Updated on July 4, 2024

Article Outline

Operator behavior for user-defined types, such as structures and objects, can be modified in C++. We refer to this as operator overloading in C++. 

 

Assume, for instance, that we have constructed three objects, c1, c2, and c3, which are members of the Complex class, which stands for complex numbers. That’s what operator overloading is. 

 

Keep reading this article to learn more about the basics of operator overloading in C++. 

 

What is Operator Overloading in C++

 

Operator overloading in C++ refers to the ability to redefine or customize the behavior of certain operators when they are used with user-defined data types (classes and structs). This allows you to provide a specific meaning or action for operators beyond their built-in functionality. Basically, Overloading in C++ is the process of creating two or more members with the same name but differing numbers or types of parameters. We can overload the following in C++:

 

  • Constructors, 
  • Methods, and 
  • Indexed properties

Note: They are referred to as overload operators because these members are limited by their restrictions. 

 

*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

List of Operators that can be Overloaded in C++

 

When it comes to operator overloading in C++ program, we can overload the following operators: 

 

  • Binary operators
  • Unary operators
  • Special operators

Here is a table representing all the operators with examples that you can overload in C++: 

 

Unary arithmetic operators –, ++, -, +
Binary arithmetic operators %, /, *, -, +
De-referencing operator (->)
Bitwise operator ^, ~, >>, <<, |, &
Assignment operator %=, -=, /=, *=, +=, =
Subscript operator [ ]
De-allocation New, delete
Relational operator >=. <=, ==, <, >
Logical operator !, | |, &
Function Call ()

The Syntax for Overloading Operators in C++

When it comes to operator overloading in C++, you’ll have to use the unique operator function. It defines the function within the structure or class that comprises the variables and objects that it will need. Here’s the syntax that you need to remember: 

class className { ... .. ... public returnType operator symbol (arguments) { ... .. ... } ... .. ... };

Here,

 

  • The keyword is the operator.
  • The return type of the function is ‘returnType.’
  • The arguments passed to the function are arguments.
  • The operator is nothing but the symbol that you need to overload.

 

Types of Overloading in C++

There are two types of overloading in C++:

  • Function overloading
  • Operator overloading

 

  • Function Overloading In C++:
    In C++, function overloading is the approach of having multiple functions with similar name but unique and ranging argument values. It involves either leveraging a varied number of parameters or a unique type of argument to redefine the function. The compiler can only distinguish between the functions through these differences. 

 

  • Operator Overloading In C++:
    In a compile-time polymorphism known as operator overloading, the operator is overloaded to give the user-defined data type a special meaning. The majority of the operators available in C++ are overloaded or redefined using operator overloading. For instance, C++ offers the option to apply user-defined data types to built-in data types by adding user-defined data type variables. 

Difference Between Member Functions And Non-Member Functions For Operator Overloading

Here is a table representing the key differences between member functions and non-member functions for operator overloading in C++: 

Basis Non-Member Functions Member Functions
Arguments This operator overloading function requires two arguments – the right-hand and the left-hand operand.  This operator overloading function requires a single argument for the object where the operator is applicable.
Scope This operator function isn’t a member of the class in C++ This operator function is a member of the class in C++.
Friend Function We cannot declare any non-member function as the friend function. We can declare the member function as the friend function, enabling it to access the class’s private members.
Access Modifier Can be declared in public only Can be declared in public and have an access modifier too.

Overloading Arithmetic Operators

 

Using too many arithmetic operators is a common example of operator overloading. Thanks to this ability, you can then add, subtract, multiply, and divide items belonging to your own classes. The definition of a function with the same name as the arithmetic operator is required to overload the operator. 

 

The operator and function must have the same amount of arguments and accept arguments of the same type. You would construct a function like this, for instance, to overload the + operator for the MyClass class: 

 

MyClass operator+(const MyClass& lhs, const MyClass& rhs) { // Do some arithmetic to add the two objects together return MyClass(lhs.x + rhs.x, lhs.y + rhs.y); }

This function creates a new object of the type MyClass from two objects of the same type as parameters. The function can then perform any arithmetic operations required to combine the two objects. Once the operator function has been established, you can use the operator as usual. 

 

Read more about: What is Arrays in C, C++

 

Overloading Comparison Operators

 

A feature of C++ called operator overloading lets you specify how operators behave for user-defined types. This can be helpful for adding functionality to your classes and making your code more legible and concise. 

 

The practice of using too many comparison operators is known as operator overloading. This enables you to compare items belonging to the same classes and determine if they are equal, less than, or larger than one another. 

 

You must define a function with the same name as the comparison operator to overload it. The parameters in the function must be of the same type as the operator’s operands and equal in number to those in the operator. 

 

For instance, you might define a method that looks like this to overload the == operator for the MyClass class: 

 

id="Examples">bool operator==(const MyClass& lhs, const MyClass& rhs) { // Do some comparison to see if the two objects are equal return lhs.x == rhs.x && lhs.y == rhs.y; }

This function produces a boolean value and requires two objects of the type MyClass as parameters. If the two objects are equal, the function can perform any required comparison operations. 

 

Examples of Operator Overloading in C++

 

Below are some of the examples of Operator Overloading in c++ in detail:

 

A C++ Program to Overload a Prefix Decrement Operator

 

#include using namespace std; class OverLoad { private: int a; int b; public: OverLoad() : a(0), b(0) {} void in() { cout << "Enter the first number : "; cin >> a; cout<< "Enter the second number : "; cin >> b; } // Overload the prefix decrement operator void operator-- () { a= --a; b= --b; } void out() { cout<<"The decremented elements of the object are: ">>endl>> a>>" and " >>b; } }; int main() { OverLoad obj; obj.in(); --obj; obj.out(); return 0; } Output Enter the first number: 56 Enter the second number: 234 The decremented elements of the objects are: 55 and 223

Overloading a NOT (!) Operator

 

#include using namespace std; class NotOp { private: int a; bool b; public: NotOp() : a(0), b(true) {} void in() { cout << "Enter the first number : "; cin >> a; cout<< "Enter true or false : "; cin >> b; } // Overloading the NOT (!) operator void operator ! () { a= !a; b= !b; } void out() { cout<<"Output: ">>endl>> a>>endl>>b; } }; int main() { NotOp obj; !obj; obj.out(); return 0; } Output 1 0

What are the Rules for Operator Overloading in C++?

 

Below are the major rules for Operator Overloading in C++:

 

  • Rule 1: We cannot overload the new operators. It can only be done for the pre-existing operators. The overloaded operator consists of a minimum of one operand of the user-defined data type.
  • Rule 2: We cannot use the friend function to overload certain operators. Nevertheless, we can deploy the member function to overload such operators. 
  • Rule 3: When we use the member function to overload the unary operators, they take no explicit arguments. However, we need at least a single argument when overloading them using the friend function. 
  • Rule 4: You’ll require one explicit argument while overloading binary operators leveraging the member function. You’ll require two explicit arguments for overloading these operators using the friend function. 

 

Advantages and Disadvantages Operator Overloading in C++

 

Below are the advantages and disadvantages of Operator Overloading in C++ in detail:

 

Pros of Operator Overloading In C++:

 

  • Programmers can utilize notation more closely related to the target domain thanks to operator overloading in C++. 
  • They offer comparable support for user-defined types as built-in types do. 
  • In C++, operator overloading facilitates program comprehension. 

 

Cons of Operator Overloading In C++:

 

  • There are certain exceptions to the rule of operator overloading, which applies to all existing C++ operations.

 

Learn More: Advantages and Disadvantages of Arrays in C, C++ and Java!

 

Conclusion

 

In this guide we have learned all about Operator Overloading in C++. Basically, Operator overloading in C++ enables you to give users of your class an intuitive user interface and makes it possible for templates to work equally well with classes and built-in/intrinsic types. 

 

Given the features like operator overloading and classes, C/C++ operators can now possess user-defined meanings for user-defined types. Wish to learn more about operator overloading and other concepts of C++? Enrol in HeroVired’s Data Science & Analytics Course today! 

 

 

 

FAQs
In C++, the ability to define several definitions for a function name or an operator in the same scope is known as overloading of both the function and the operator. This sort of polymorphism overloads an operation to give it user-defined semantics.
An operator is overloaded in this type of polymorphism to give it user-defined semantics. Function as well as operator overloading are two terms used in C++ to describe the ability to specify multiple definitions for a function name or an operator in the same scope.
Function overloading and operator overloading are the two main types of overloading in C++.
Using a single name and adding more functionality to it is known as function overloading. Operator overloading refers to giving a certain operator more capability. Depending on the nature of its operands, an overloaded operator can have a variety of interpretations.

Updated on July 4, 2024

Link

Upskill with expert articles

View all
Free courses curated for you
Basics of Python
icon
5 Hrs. duration
icon
Beginner level
icon
9 Modules
icon
Certification included
avatar
1800+ Learners
View
Essentials of Excel
icon
4 Hrs. duration
icon
Beginner level
icon
12 Modules
icon
Certification included
avatar
2200+ Learners
View
Basics of SQL
icon
12 Hrs. duration
icon
Beginner level
icon
12 Modules
icon
Certification included
avatar
2600+ Learners
View
next_arrow
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved