Javatpoint Logo
Javatpoint Logo

C++ Program to concatenate two strings using Operator Overloading

String concatenation refers to the collection of characters that join two additional strings to produce a concatenated single string. While concatenating the strings, the second string is appended to the end of the first string to form a single string.

Example:

Approach 1: By using the Unary Operator Overloading

  • Unary operator overloading is used to concatenate two strings. Create a class that has two string parameters.
  • Please create a new instance of the class and use its parameterized constructor to initialize the two string parameters with the main function's input values.
  • Use the unary operator + to combine these two string parameters for a class instance.
  • Finally, use the operator method to join two class variables.

The previously mentioned technique is implemented as follows:

Example:

Filename: OperatorOverloading.cpp

Output:

The Concatenation form of the string: OperatorOverloading

Explanation:

  • In this example, a class called AddingString is used to concatenate strings. It stores the input strings in two member variables, st1 and st2. The supplied strings are used by the constructor AddingString for initializing st1 and st2. The operator "+ "function has been overloaded to use strcat() to conduct string concatenation and show the result.
  • Two strings, string1, and string2, are initialized by the main function. Using string1 and string2, it generates an object op of the AddingString The concatenation is then started, and the result is printed by calling the operator "+" function with the unary "+" operator using the op object.

Approach 2: By using binary operator overloading

Create a class that has a string variable and an operator function called "+" that takes an instance of the class's members as input and combines the variable of that instance with the present instance's string variable.

Make two separate instances of the class and initialize both of the input strings in each instance's class variable.

The class variable of each of the instances should now be concatenated using the overloading operator (+) function.

Example:

Filename:Binary.cpp

Output:

The Concatenated form of the string is: ProgrammingSubjects






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA