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:

  1. <return_type>operator(arg1,agr2,…..,argun)
  2. {
  3. //task for user define
  4. }

Rules for Operator Overloading

There are certain restrictions and limitations in operator overloading. Some of them 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.

  1. #include<iostream>
  2. #include<conio.h>
  3. using namespace std;
  4. class String
  5. {
  6. char str[20]; //member variable for string input
  7. public:
  8. void input() //member function
  9. {
  10. cout<<"Enter your string: ";
  11. cin.getline(str,20);
  12. }
  13. void display() //member function for output
  14. {
  15. cout<<"String: "<<str;
  16. }
  17. String operator+(String s) //overloading
  18. {
  19. String obj;
  20. strcat(str,s.str);
  21. strcpy(obj.str,str);
  22. return obj;
  23. }
  24. };
  25. void main()
  26. {
  27. String str1,str2,str3; //creating three object
  28. str1.input();
  29. str2.input();
  30. str3=str1+str2;
  31. str3.display(); //displaying
  32. getch();
  33. }
Concatenate Two String Using Binary Operator Overloading

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.