string concatenation operator overloading c++
#include <iostream>
#include <string>
class MyString {
private:
std::string str;
public:
MyString() : str("") {}
MyString(const std::string& s) : str(s) {}
MyString operator+(const MyString& other) {
MyString result;
result.str = this->str + other.str;
return result;
}
void display() {
std::cout << str << std::endl;
}
};
int main() {
MyString str1("Hello, ");
MyString str2("world!");
MyString result = str1 + str2;
result.display();
return 0;
}
Explanation:
Header Inclusions: The code includes necessary headers like
<iostream>
for input/output and<string>
for string operations.MyString Class Definition:
MyString
is a custom class that encapsulates a string (std::string str
).- It has a default constructor
MyString()
that initializesstr
as an empty string, and another constructorMyString(const std::string& s)
that initializesstr
with a given string.
Overloading
+
Operator:operator+
is overloaded inside theMyString
class to concatenate twoMyString
objects.- It takes another
MyString
object (other
) as a parameter and returns a newMyString
object containing the concatenated string.
display
Function:display()
method prints the content of theMyString
object to the console.
main
Function:- Inside
main()
, twoMyString
objectsstr1
andstr2
are created with initial strings "Hello, " and "world!" respectively. - The
+
operator is used to concatenatestr1
andstr2
, resulting in a newMyString
objectresult
. result.display()
displays the concatenated string ("Hello, world!") to the console.
- Inside