1

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?

5
  • 4
    What you are trying ot do is not constructor overloading, but operator overloading. Commented Nov 7, 2012 at 20:38
  • Also do 'a' and 'b' contain real strings? You may be calling strlen on NULL or uninitialized pointers. Commented Nov 7, 2012 at 20:41
  • typedef String std::string; Commented Nov 7, 2012 at 20:43
  • If you're going to implement your own string class IMO you ought to at least make it 8-bit clean (i.e. not-null terminated). Commented Nov 7, 2012 at 20:43
  • 1
    I'm guessing Rule of Three. Commented Nov 7, 2012 at 20:44

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I didn't have a copy constructor. In my function rez was exactly what I wanted but I was returning the pointer that was deleted by destructor at the end of the function. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.