Question:
I am puzzled at the way in which the assignment operator is overloaded in C++. Would you please show an example as to what efficient code for overloading this operator would look like. Specifically, my confusion is about how this function would copy old resources into new resources before return *this.
Answer:
The copy assignment operator for a class must do the following.
- make sure that all members are copied.
- make sure it calls assignment on any base classes it inherits from
- be safe from assignment to self.
lets consider a sample string class.
e.g.
// class string inherits from some class called datatype
class string : public datatype
{
public:
string(char *str,int len)
{
data_ = new char [len+1];
strncpy(data_,str,len)
data_[len] = '\0';
}
~string() {delete [] data_;}
const string& operator = (const string &rhs)
{
// this is necessary else stuff later will destroy the
// data_ so we'll loose information
if(&rhs != this)
{
// call base classes assignment operator
datatype::operator =(rhs);
// copy over data members
delete [] data_;
data_ = new char[strlen(rhs.data_)];
strcpy(data_,rhs.data_);
}
// finally return referance to self
return *this;
}
private:
char * data_;
};
Note that it is very important to check for
&rhs != this, other wise
if some one wrote a = a where a is a string object we would delete
data_ and thus invalidate the object..
also note that I prefer to return a const referance to self from the
copy assignment operator. This prevents code like (a = b) = c from
compiling.
hope that helps
-bom
C++Pro