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 #include #include #include 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; }
Declaring and Initializing Local Variable in C
Declaring and Initializing Global Variable in C Language
Printf Function In C Language
Sacnf Function In C Language
for Loop in C Language
While Loop in C Language
Do While Loop in C Language
Switch Case Statement IN C
IF -Else Statement IN C
Break Statement IN C /C++
User Define Function IN C /C++
Cout/Cin Function IN C /C++
Array IN C /C++
Two Dimensional Array IN C /C++
String In IN C /C++
Pointer In IN C /C++
Const and volatile keyword IN C /C++
Class and Object in C++
Function Over Loading in C++
Character Array In C++
Constructor in C++
Operator overloading in C++
Function Templates in C++
ATM Sample Project In Simple C Language
Find Area of Shape Using Function In C++