C++ Program to concatenate two strings using Operator Overloading
Palavras-chave:
Publicado em: 09/08/2025C++ String Concatenation with Operator Overloading
This article explores how to concatenate two strings in C++ using operator overloading. Operator overloading allows us to redefine the behavior of operators, such as the `+` operator, to work with user-defined types like our own string class. This can make our code more readable and intuitive.
Fundamental Concepts / Prerequisites
Before diving into the code, it's essential to understand the following concepts:
- C++ Classes: You should be familiar with defining classes, creating objects, and using member functions.
- Operator Overloading: Understanding how to overload operators in C++ is crucial. Specifically, you should know how to declare an operator function within a class and how to define its behavior.
- String Handling in C++: A basic understanding of string manipulation, including copying strings, is helpful.
Implementation in C++
#include
#include
class MyString {
private:
char* str;
int len;
public:
// Constructor
MyString(const char* s = "") {
len = std::strlen(s);
str = new char[len + 1];
std::strcpy(str, s);
}
// Copy Constructor
MyString(const MyString& other) {
len = other.len;
str = new char[len + 1];
std::strcpy(str, other.str);
}
// Destructor
~MyString() {
delete[] str;
}
// Overload the + operator
MyString operator+(const MyString& other) const {
int newLen = len + other.len;
char* newStr = new char[newLen + 1];
std::strcpy(newStr, str);
std::strcpy(newStr + len, other.str);
return MyString(newStr); // Create a temporary MyString object to return
}
// Assignment operator overload
MyString& operator=(const MyString& other) {
if (this != &other) { // Prevent self-assignment
delete[] str;
len = other.len;
str = new char[len + 1];
std::strcpy(str, other.str);
}
return *this;
}
// Method to display the string
void display() const {
std::cout << str << std::endl;
}
};
int main() {
MyString str1("Hello");
MyString str2(" World");
MyString str3 = str1 + str2; // Concatenate str1 and str2
str3.display(); // Output: Hello World
MyString str4("!");
str3 = str3 + str4;
str3.display(); // Output: Hello World!
MyString str5;
str5 = str1;
str5.display(); // Output: Hello
return 0;
}
Code Explanation
Let's break down the code:
1. `class MyString`: This defines our custom string class. It holds a character array (`str`) and its length (`len`).
2. `Constructor (MyString(const char* s = ""))`: This constructor initializes a `MyString` object from a C-style string. It allocates memory for the string and copies the content using `std::strcpy`.
3. `Copy Constructor (MyString(const MyString& other))`: This constructor creates a new `MyString` object by copying another `MyString` object, ensuring proper memory management to prevent shallow copies.
4. `Destructor (~MyString())`: The destructor releases the memory allocated for the string when a `MyString` object is destroyed. This prevents memory leaks.
5. `Operator Overloading (MyString operator+(const MyString& other) const)`: This is the core of our solution. We overload the `+` operator. It creates a new string (`newStr`) with the combined length of the two strings. It then copies the contents of the original strings into the new string using `std::strcpy`. Finally, it creates and returns a *new* `MyString` object initialized with the concatenated string. The `const` at the end of the function signature ensures that the operator does not modify the original objects (str1 and str2 in the example). The `const` on the parameter means that the other MyString argument will not be modified.
6. `Assignment Operator Overloading (MyString& operator=(const MyString& other))`: Handles assignment between `MyString` objects. It prevents self-assignment, deallocates the existing string, and allocates new memory to copy the content from the `other` `MyString`.
7. `display()`: A simple member function to print the string to the console.
8. `main()`: The `main` function demonstrates how to use the overloaded `+` operator to concatenate two `MyString` objects.
Complexity Analysis
Time Complexity: The time complexity of the `operator+` function is O(n + m), where n and m are the lengths of the two strings being concatenated. This is because we need to copy the characters of both strings into the new string.
Space Complexity: The space complexity is also O(n + m), as we allocate a new string of size n + m to store the concatenated result. The copy constructor and assignment operator also exhibit similar complexities due to memory allocation and string copying.
Alternative Approaches
Another approach would be to use `std::string` from the standard library. This class handles memory management automatically and provides a built-in `+` operator for concatenation. While this approach avoids the need to write custom memory management code, using `std::string` might have a slight performance overhead compared to a carefully optimized custom string class, especially for specific concatenation-heavy applications. However, `std::string` generally provides a more robust and safer solution.
Conclusion
Operator overloading provides a powerful way to customize the behavior of operators for user-defined types. By overloading the `+` operator for our `MyString` class, we were able to create a more intuitive and readable syntax for concatenating strings. However, it's crucial to manage memory carefully when dealing with dynamic memory allocation to prevent memory leaks. Using the standard library's `std::string` offers a simpler and safer alternative, though it might come with minor performance tradeoffs in certain situations.