Sorin
Sorin

Reputation: 910

C++ Overloading operator +()

I have a simple class called String which has as a private field a char*.

class String {
      char *s;
+ some public methods
};

I want to overload the + operator so a + b would mean that the strings from a and b are concatenated.

The function is here:

String String::operator+(String a)
{
    String rez;
    rez.s = new char[strlen(this->s) + strlen(a.s) + 1];
    assert(rez.s);
    strcpy(rez.s, this->s);
    strcat(rez.s, a.s);
    cout<<rez.s<<endl; // HERE rez.s CONTAINS THE RIGHT STRING!
    return rez;
}

After I call this: c = a + b;

i get an error called Debug assertion failed.

Any ideas?

Upvotes: 1

Views: 162

Answers (1)

WhozCraig
WhozCraig

Reputation: 66204

First, read up on the Rule of Three

Then, consider this:

class String {
      char *s;   // << pointer
+ some public methods
};

"+ some public methods" better have a constructor that initializes the pointer member to a testable value (like NULL) or you're well-into undefined behavior. It better override the copy-constructor and assignment operators to properly duplicate the string from one String object to another. Finally, it better have a destructor that knows how to clean up a dynamic pointer to the content allocated in all of the above.

I strongly suggest you read that article backwards and forwards.

Upvotes: 1

Related Questions