I would like to ask some question. I am taking OOP C++ course in my faculty. We had some exercise connected with reinitializing dynamicly allocated char array. The problem is as follows:
class state
{
private:
char *szstate; // a name of object
public:
state &operator = (const state&);
};
state & state::operator = (const state &cop)
{
if (this != &cop)
{
szstate = new char [strlen(cop.szstate)+strlen("==.")+1];
strcpy(this->szstate,"==.");
strcat(this->szstate, cop.szstate);
return *this;
}
else return *this;
}
In shortcut, creating an object "a" with the name "DEFAULT" and after b = a, should give me object b with name "==.DEFAULT". This will need more memory, so I used operator new for safety. The thing is that teacher said there should be also
delete []szstate
before I reinitialize the "name" of object - I tried this, but segmentation fault appeared. Anyway, I found some writing in Stephen Prata's book, where he wrote that char* shall remain untouched; char* shall be treated as unchangeable constant, so that will be some kind of explanation for the error. So, am I doing something wrong or the teacher have no right? Thanks for the answers :)