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

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may