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);
}

Recommended Answers

All 3 Replies

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 ?

its all good i was able to fix my problem

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.