devxlogo

Overloading the assignment operator “=”

Overloading the assignment operator “=”

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.

  1. make sure that all members are copied.
  2. make sure it calls assignment on any base classes it inherits from
  3. be safe from assignment to self.
lets consider a sample string class.e.g.
// class string inherits from some class called datatypeclass string : public datatype{public:	string(char *str,int len)	{		data_ = new char [len+1];		strncpy(data_,str,len)		data_[len] = ‘’;	}	~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 wiseif 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 thecopy assignment operator. This prevents code like (a = b) = c fromcompiling.hope that helps-bomC++Pro

See also  Essential Measures for Safeguarding Your Digital Data
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist