I have to do a homework that requires operator overloading. It's very simple , but i think i forgot alot about operator overloading.
I need to make a premitive string-like class that only has overloaded + and = signs.
Here's the header file :
StrType(char * = "\0");
StrType &operator=(const StrType &);
StrType operator+(const StrType &);
and the .cpp file :
Am i using the proper return types? My C++ book says that = should return a const reference of an object , but that doesn't make sense to me. Also , my operator= function always fail when trying to delete 'ptr' and show an error "debug assertion failed" in VC++. (hilighted in red)
ptr = new char[strlen(str) + 1];
StrType &StrType::operator=(const StrType &right)
if( &right != this)
delete  ptr; // error always occur here
ptr = new char[strlen(right.ptr) + 1];
StrType StrType::operator+(const StrType &right)
char *temp = new char[strlen(right.ptr) + strlen(ptr) + 1];
delete  ptr;
ptr = new char[strlen(temp) + 1];
delete  temp;
cout << ptr;
delete  ptr;
I used to return a reference to an object in operator+ till i noticed that ' a = b + c + d' would modify objects b , c and d , so i let it return a copy of the object instead.
I just need help in those two operator's logic and return value.