Operator Overloading in C++
In C++, you can alter the way operators work for user-defined types like objects and structures. This is known as operator overloading. It is one of the best features used to redefine the operators in C++ such as +, -, *, /, etc.
One operator can have multiple definition. Like + can be used to add two numbers and can also be used to add two words when used with string. In this article, we will learn how to use operator overloading in C++ and its implementation. This article will cover the following sections:
- What is Operator Overloading in C++?
- C++ Operators that can be Overloaded
- Examples of Operator Overloading in C++
Explore free C++ courses
What is Operator Overloading in C++?
C++ allows us to specify more than one definition for an operator in the same scope, which is called Operator Overloading. It is basically the process of assigning additional functionality and behaviour to pre-existing C++ operators [insert link here]. By default, these operators work only on standard data types such as int, float, char, void, etc.
You can also explore: OOPs concepts in C++
The process of selecting the most suitable overloaded operator is called overload resolution.
In C++, operator overloading represents the compile-time polymorphism or static binding as overloading occurs during compile time.
C++ Syntax to implement operator overloading:
//Function Overriding in C++
class className { ... .. ... public returnType operator symbol(parameters) { ... .. ... } ... .. ... };
Where,
- returnType is the return type of the function.
- operator is a keyword.
- symbol is the operator we want to overload. For example, +, -, *, <, ++, etc.
- parameters are the parameters of the function.
Best-suited C++ courses for you
Learn C++ with these high-rated online courses
C++ Operators that can be Overloaded
Most operators in C++ can be overloaded except for a few. Following is the list of operators that can be overloaded:
- Unary Arithmetic Operators such as: +, -, ++, —
- Binary Arithmetic Operators such as: +, -, *, /, %
- Assignment Operators such as: =, +=, *=, /=, -=, %=
- Bitwise Operators such as: &, |, <<, >>, ~, ^
- Logical Operators such as: &, ||, !
- Relational Operators such as: >, <, ==, <=, >=
- De-referencing Operator: (->)
- Dynamic memory allocation and De-allocation Operators: New, delete
- Subscript Operator: []
- Function call: ()
The operators that cannot be overloaded are given below:
- Scope Operator: (::)
- Size-of Operator: sizeof()
- Member Selector: (.)
- Member Pointer Selector: (*)
- Ternary Operator: (? : )
You can also explore: Constructors in C++ and its Types
Operator Overloading in C++ Examples
Example 1: Unary (++) Operator Overloading
#include using namespace std; class count { private: int val; public: //Constructor to initialize count to 10 count() : val(10) {} //Overload ++ when used as prefix void operator ++() { ++val; } //Overload ++ when used as postfix void operator ++(int) { val++; }
void display() { cout << "Count: " << val << endl; } }; //Driver code int main() { count c1; //Call the "void operator ++ (int)" function c1++; c1.display(); //Call the "void operator ++ ()" function ++c1; c1.display(); return 0; }
Output 1:
What have we done here?
In the above example, we have used the unary operator (++) as both prefix and postfix.
Since the return type of our operator function is void, we need to make count as the return type of the operator function for the code to work.
Example 2: Binary (+) Operator Overloading
// C++ program to add two complex numbers #include using namespace std; class complex { private: float real; float img; public: //Constructor to initialize real and imag to 0 complex() : real(0), img(0) {} void input() { cout << "Enter the real and imaginary parts of the number respectively: "; cin >> real; cin >> img; } //Overload the + operator complex operator +(const complex& obj) { complex temp; temp.real = real + obj.real; temp.img = img + obj.img; return temp; } void output() { if (img < 0) cout << "Output Complex number: " << real << img << "i"; else cout << "Output Complex number: " << real << "+" << img << "i"; } }; //Driver code int main() { complex c1, c2, result; cout << "First complex number- \n"; c1.input(); cout << "Second complex number- \n"; c2.input(); //c1 calls the operator function //c2 is passed as an argument to the function result = c1 + c2; result.output(); return 0; }
Output 2:
What have we done here?
Note that we make use of & in our code to make it more efficient by referencing the complex c2 object instead of making a duplicate object inside the operator function.
Also, using the keyword const is considered to be a good practice as it prevents the operator function from modifying complex c2 object.
Points to remember:
- For operator overloading to work, at least one of the operands must be a user-defined class object.
- Operator overloading cannot affect the order of precedence and associativity of the operators. However, to change the order of evaluation, you can use parentheses ().
- The operators = and & are already overloaded in C++ by default. So, if you want to copy objects of the same class, you can directly use the = operator and need not define an operator function.
You can also explore: Top C++ Interview Questions and Answers
Endnotes
In C++, there are two types of overloading: function overloading and operator overloading. We have covered the latter in this article. Hope this article helped you understand how operator overloading works in C++. If you want to learn more about C++ and solidify your basics, you can explore our articles on the C++ programming language.
FAQs
What is operator overloading in C++?
Operator overloading is a feature in C++ that allows operators such as +, -, *, /, =, and many others to be redefined for user-defined classes or structures. This makes it possible to use these operators with objects of these classes, providing a natural and intuitive syntax for manipulating the objects.
Why is operator overloading important?
Operator overloading can make code more readable and intuitive, as it allows users to manipulate objects using familiar operators. It can also simplify code by reducing the number of functions that need to be defined, making it easier to write and maintain code.
Which operators can be overloaded in C++?
C++ allows a wide variety of operators to be overloaded, including arithmetic operators (+, -, *, /), comparison operators (==, !=, , =), logical operators (!, &&, ||), assignment operators (=, +=, -=, *=, /=), and others.
How is operator overloading implemented in C++?
Operator overloading is implemented by defining a special function called an "operator function" that takes one or more objects of a user-defined class as arguments. This function is typically defined as a member function of the class, although it can also be defined as a standalone function.
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio