Ok look , i have a simple string class with overloaded '+=' , '=' and '+'. The '+=' and '=' work just fine when i use them with object. But the friggin '+' sign is still causing troubles !!!
I spent like 1 hour on this crap and i still can't figure out how to get around this "Debug Assertion Failed" error (vc++). I tracked execution and found that the problem occurs when one of the objects (don't know which) tries to delete it's sPtr space.
anyway , the following are my .h , .cpp and main.cpp files. The problem is probably in the operator+ function (hilihgted in blue) , i posted the whole code just incase you need to take a look at something else :
mystr.hCode:#ifndef MYSTR_H #define MYSTR_H class mystr { public : mystr(const char * = ""); ~mystr(); const mystr &operator+=(const mystr &); const mystr &operator=(const mystr &); mystr operator+(const mystr &); void print(); private : int length; char *sPtr; }; #endifmystr.cppCode:#include <iostream> using std::cout; using std::endl; #include <cstring> #include "mystr.h" mystr::mystr(const char *s) // default constructor { length = strlen(s); sPtr = new char[ length + 10 ]; strcpy(sPtr, s); } mystr::~mystr() // destructor { delete [] sPtr; } const mystr &mystr::operator +=(const mystr &right) { size_t newLength = length + right.length; char *tempPtr = new char[newLength + 1]; strcpy(tempPtr, sPtr); strcpy(tempPtr + length, right.sPtr); delete [] sPtr; sPtr = tempPtr; length = newLength; return *this; } mystr mystr::operator+(const mystr &right) { mystr temp(sPtr); temp += right; return temp; } const mystr &mystr::operator=(const mystr &right) { if( &right != this) { delete [] sPtr; sPtr = new char[right.length + 1]; strcpy(sPtr, right.sPtr); } return *this; } void mystr::print() { cout << sPtr << endl; }main.cppCode:#include "mystr.h" int main(void) { mystr a("hello"), b("world\n"), c; a.print(); b.print(); c = a + b; c.print(); return 0; }
it only displays :
hello
world
then shows an error. I hope someone can help before i tear the rest of my hair out.
p.s : please don't give examples , just show me how to fix my my code.