⟩ Tell me 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.
class String
{
char *s;
int sz;
public:
String(int n)
{
size = n;
s = new char [n];
}
void accept()
{
cout <<”n Enter String:”;
cin.getline(s, sz);
}
void display()
{
cout<<”The string is: ”<<s;
}
String operator +(String s2) // ‘+’ operator overloaded
{
String ts(sz + s2.sz);
for(int i = 0; s[i]!=’ ’;i++)
ts.s[i] = s[i];
for(int j = 0; s2.s[j]!=’ ’; i++, j++)
ts.s[i] = s2.s[j];
ts.s[i] = ‘ ’;
return ts;
}
};
int main()
{
String s1, s2, s3;
s1.accept();
s2.accept();
s3 = s1 + s2; //call to the overloaded ‘+’ operator
s3.display()
}
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.