I have to write one new class with members something like
class A
{
static int i;
const int j;
char * str;
...
...
};
Now I want to write assignment operator for it.
A& A::operator=(const A& rhs)
{
if(this != rhs)
{
delete [] str;
str = new char[strlen(rhs.str)+1];
strcpy(str, rhs.str);
}
return * this;
}
Is it right? I shall ignore the static and const members(?).
The assignment operator copies one object into another. Since all objects of the same type share the same static members, there’s no reason to copy the static members.
constmembers are another matter. You can’t (well, shouldn’t) change them, but if two objects have different values for a const member, it might not be a good idea to copy one object into another; the const member won’t have the right value. That’s why the compiler doesn’t generate a copy assignment operator for classes that have const members. So you first have to be sure that copying such an object makes sense, even with the wrong value for the const members; and then ask yourself why it has const members if they don’t affect how it behaves.References too. (yes, there’s an echo in here)