0

For my custom string class for a class assignment I have the += operator figured out from a previous question but I want to know how to implement the + operator. would I follow similar procedures?

I have already finished the += operator but I want to know how to do the + operator. I have attached the += operator and the signature for the + operator.

DSString operator+(const DSString& src)
{


}

DSString& DSString::operator+=(const DSString& src){
    if(src.data != nullptr) {
        char *tmp = new char[length + src.length + 1];
        strcpy(tmp, data);
        strcat(tmp, src.data);
        length = length + src.length;
        delete [] data;
        data = tmp;
    }
     return *this;


}

I am expecting the string to be able to concatenate together but I have no idea if I can reuse code that I already have or need to start something new.

2 Answers2

2

You can define that operator using the += that you just defined;

{
  DSString tmp = *this;
  return tmp += src;
} 

Probably not the most efficient, though...

Roddy
  • 66,617
  • 42
  • 165
  • 277
-1

I'm no expert but I did it the other way around every time.

Defining the '+' operator that returns a new Object. Defining the '+=' operator that uses the '+' and returns the new Object in 'this'.