Program to overload ‘+’ operator for concating the strings
Operator overloading in C++ allows you to redefine how operators work with user-defined types. In this tutorial, we will write a C++ program to overload the + operator for a custom string class to concatenate two strings. This is a classic use case of operator overloading that enhances the readability and functionality of your C++ code.
#include<iostream.h>
#include<string.h>
class string{
int len;
char *name;
public:
string()
{
len = 0;
name = new char[1];
}
string(char *s)
{
len = strlen(s);
name = new char[len+1];
strcpy(name,s);
}
void display()
{
cout<<name<<endl;
}
friend string operator +(string t, string s);
};
string operator +(string t, string s)
{
string temp;
temp.len = t.len+s.len;
temp.name = new.char[temp.len+1];
strcpy(temp.name t.name);
strcat(temp.name, s.name);
return temp;
}
int main()
{
char a[10],b[10];
cout<<"Enter the string S1:"; cin>>a;
string s1(a);
cout<<"enter the string S2: "; cin>>b;
string s2(b);
string s3=s1+s2;
cout<<"\n ......OUTPUT......\n";
cout<<"\n S1= ";
s1.display();
cout<<"\n S2= ";
s2.display();
cout<<"\n S1+S2= ";
s3.display();
return(0);
}
OUTPUT Enter the string S1: new Enter the string S1: york ......OUTPUT...... S1 = new S2 = york S1+S2= newyork
Benefits of Operator Overloading:
- Makes code intuitive and cleaner
- Mimics built-in type operations on custom classes
- Improves code modularity and reusability
Conclusion:
Overloading the + operator to concatenate strings in C++ is a practical example of making your class behave like a built-in data type. It helps you understand the power and flexibility of object-oriented programming in C++.


