Pre-requisite: Operator Overloading in C++ Given two strings. The task is to concatenate the two strings using Operator Overloading in C++.
Example:
Input: str1 = "hello", str2 = "world"
Output: helloworld
Input: str1 = "Geeks", str2 = "World"
Output: GeeksWorld
Approach 1 : Using unary operator overloading.
To concatenate two strings using unary operator overloading. Declare a class with two string variables.
Create an instance of the class and call the Parameterized constructor of the class to initialize those two string variables with the input strings from the main function.
Overload the unary operator to concatenate these two string variables for an instance of the class.
Finally, call the operator function and concatenate two class variables.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <string.h>
using namespace std;
class AddString {
public:
char s1[25], s2[25];
AddString(char str1[], char str2[])
{
strcpy(this->s1, str1);
strcpy(this->s2, str2);
}
void operator+()
{
cout << "\nConcatenation: " << strcat(s1, s2);
}
};
int main()
{
char str1[] = "Geeks";
char str2[] = "ForGeeks";
AddString a1(str1, str2);
+a1;
return 0;
}
Output:
Concatenation: GeeksForGeeks
Approach 2: Using binary operator overloading.
Declare a class with a string variable and an operator function ‘+’ that accepts an instance of the class and concatenates it’s variable with the string variable of the current instance.
Create two instances of the class and initialize their class variables with the two input strings respectively.
Now, use the overloaded operator(+) function to concatenate the class variable of the two instances.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <string.h>
using namespace std;
class AddString {
public:
char str[100];
AddString() {}
AddString(char str[])
{
strcpy(this->str, str);
}
AddString operator+(AddString& S2)
{
AddString S3;
strcat(this->str, S2.str);
strcpy(S3.str, this->str);
return S3;
}
};
int main()
{
char str1[] = "Geeks";
char str2[] = "ForGeeks";
AddString a1(str1);
AddString a2(str2);
AddString a3;
a3 = a1 + a2;
cout << "Concatenation: " << a3.str;
return 0;
}
Output:
Concatenation: GeeksForGeeks
Level Up Your GATE Prep!
Embark on a transformative journey towards GATE success by choosing
Data Science & AI as your second paper choice with our specialized course. If you find yourself lost in the vast landscape of the GATE syllabus, our program is the compass you need.
Last Updated :
17 May, 2021
Like Article
Save Article