C++ Programming

Operator Overloading in C++

Operator overloading is the phenomenon in which we give the capability to existing C++ operators to operate on data type over which they cannot operate ordinarily. So, operator overloading enables the existing operators to perform in different ways.

Suppose we want to add two integer values. We may write the following segment of code.

a = 45;

 b = 20;

 c= a + b;

The above addition operation is correct/valid because the operator (+) can operate on integer data (which is a built-in data type).

On the other hand, if we write the following segment of code to add two character values,

char ch1,ch2,ch3;

ch1=’a’;

ch2=’b’;

ch3= ch1 + ch2;

So, what will be the solution to such situations? The easy and simple solution to handle such situations is operator overloading in which this type of operations are made valid.

The general syntax of the function that overloads an operator is as under.


Return-type operator Operator-symbol (arguments list)
{
// body of overloading function

}

Example:


void operator ++ ()

Programming example of Operator overloading:


#include <stdio.h>
#include<conio.h>
#include <string.h>
#include<iostream>
using namespace std;
// Class to implement operator overloading
// function for concatenating the strings
class AddString
 {
	public:
	string s1;
	string s2;
	// Parametrized Constructor
	AddString(string str1, string str2)
	{
	s1=str1;
	s2=str2;
	}

	// Overload Operator+ to concat the string
	string operator+()
	{
	return(s1.append(s2));
	}
};
int main()
{
// Declaring two strings
string a1 = "hello";
string a2= "C++";
// Declaring and initializing the class
// with above two strings
AddString op(a1, a2);
// Call operator function
cout<<+op;
return 0;
}