What is operator overloading in C++?
- C++ provides ability to overload most operators so that they perform special operations relative to classes. For example, a class String can overload the + operator to concatenate two strings.
- When an operator is overloaded, none of its original meanings are lost. Instead, the type of objects it can be applied to is expanded. By overloading the operators, we can use objects of classes in expressions in just the same way we use C++’s built-in data types.
- Operators are overloaded by creating operator functions. An operator function defines the operations that the overloaded operator will perform on the objects of the class. An operator function is created using the keyword operator.
- For example: Consider class String having data members char *s, int size, appropriate function members and overloaded binary operator + to concatenate two string objects.
size = n;
s = new char [n];
cout <<”\n Enter String:”;
cout<<”The string is: ”<<s;
String operator +(String s2) // ‘+’ operator overloaded
String ts(sz + s2.sz);
for(int i = 0; s[i]!=’\0’;i++)
ts.s[i] = s[i];
for(int j = 0; s2.s[j]!=’\0’; i++, j++)
ts.s[i] = s2.s[j];
ts.s[i] = ‘\0’;
String s1, s2, s3;
s3 = s1 + s2; //call to the overloaded ‘+’ operator
- If you pass strings “Hello” and “World” for s1 and s2 respectively, it will concatenate both into s3 and display output as “HelloWorld”
Operator overloading can also be achieved using friend functions of a class.