im trying to overload the operator+= and use that to implement operator+ in my string class. i keep getting a segmentation fault when i try to evaluate something like s1 += s2 where MyString s1("");and MyString s2("hello"); any suggestions as to why this is happening?
this is my operator+= function

MyString operator+=(const MyString& s1, const MyString& s2)
{
        MyString temp;
        delete[] temp.data;
        temp.len = s1.len + s2.len;

        temp.data = new char[temp.len + 1];
        strcpy(temp.data, s1.data);
        strcat(temp.data, s2.data);

        return temp;
}

and this is my operator+ function

MyString operator+(const MyString& s1, const MyString& s2)
{
    MyString temp;
    delete [] temp.data;
    return ((temp += s1) += s2);
}

Edited 5 Years Ago by corby: n/a

Does it work with two strings of greater than zero length? If it does, you may need to test for the string length for both strings.

I have some questions about your code:-
1) Why are you using

MyString temp; // create a object and put default memory and location to data according to your constructor MyString()
              delete [] temp.data; // delete the data created by constructor

2) You are creating a local object MyString temp;(in stack) and returning the value ?

This question has already been answered. Start a new discussion instead.