Introduction
In this blog we will learn about operator overloading and see one example that concatenates two strings using binary operator overloading. Let's start.
Operator Overloading
Operator overloading is one the many exciting feature of the C++ language. It provides a special meaning to an operator. The insertion (<<) and extraction (>>) operator is the best example of operator overloading.
Operator overloading defines a different meaning to an operator, and the operator function is used. Syntax for operator overloading is below:
- <return_type>operator(arg1,agr2,…..,argun)
- {
-
- }
Rules for Operator Overloading
There are certain restrictions and limitations in operator overloading. Some of them are listed below:
- Declare the operator function in the public section in the class.
- Define the operator function to implement the required operations.
- The overloaded operators must have at least one operand that is of user-defined type.
- We cannot change the basic meaning of an operator. That is, we cannot redefine the plus (+) operator to subtract one value from the other.
- Binary arithmetic operators such as +,-,* and / must explicitly return a value.
- There are some operators that cannot be overloaded, and they are listed below:
Operator
|
Description
|
.
|
Membership operator
|
.*
|
Pointer to member operator
|
::
|
Scope resolution operator
|
?:
|
Conditional Operator
|
Sizeof
|
Sizeof operator
|
Binary Operator Overloading
A binary operator is an operator that operates on two operands. For example, the plus "+" operator is a binary operator since it operates on two operands as in:
C=A+B
Example
This example concatenating two strings using binary operator overloading.
- #include<iostream>
- #include<conio.h>
- using namespace std;
-
- class String
- {
- char str[20];
- public:
- void input()
- {
- cout<<"Enter your string: ";
- cin.getline(str,20);
- }
- void display()
- {
- cout<<"String: "<<str;
- }
- String operator+(String s)
- {
- String obj;
- strcat(str,s.str);
- strcpy(obj.str,str);
- return obj;
- }
- };
- void main()
- {
- String str1,str2,str3;
- str1.input();
- str2.input();
- str3=str1+str2;
- str3.display();
- getch();
- }
Summary
In this blog, I covered operator overloading, some restrictions for operator overloading, and saw an example that concatenates two strings using binary operator overloading in the C++ language. If you face any problems please comment. Thanks for reading.