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:

  1. Header Inclusions: The code includes necessary headers like <iostream> for input/output and <string> for string operations.

  2. MyString Class Definition:

    • MyString is a custom class that encapsulates a string (std::string str).
    • It has a default constructor MyString() that initializes str as an empty string, and another constructor MyString(const std::string& s) that initializes str with a given string.
  3. Overloading + Operator:

    • operator+ is overloaded inside the MyString class to concatenate two MyString objects.
    • It takes another MyString object (other) as a parameter and returns a new MyString object containing the concatenated string.
  4. display Function:

    • display() method prints the content of the MyString object to the console.
  5. main Function:

    • Inside main(), two MyString objects str1 and str2 are created with initial strings "Hello, " and "world!" respectively.
    • The + operator is used to concatenate str1 and str2, resulting in a new MyString object result.
    • result.display() displays the concatenated string ("Hello, world!") to the console.