ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

Overloading C++ "Assignment = Operator" with Example

Updated on May 10, 2018
sirama profile image

I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 Yrs. I like playing video games & reading books.

1. Introduction

By default, any class will have a compiler implemented copy constructor and assignment operator. In order to avoid shallow copy while we overload the copy constructor, we should overload the Assignment operator also. The syntax for the operator overloading is shown below:

Source

The left-hand side of the assignment operator will make a call to the Operator = by passing the value on the right-hand side as the parameter. The overloading function receives the parameter as the const reference as the assignment operation guarantees that the right-hand side value of the assignment operation will nevermore get changed. In this hub, we will see that how do we overload the assignment operator.

2. CPoint3d Class

Below are the private members of the CPoint3d class that we are going to experiment using the overloaded assignment operator.

//Sample 01: Private Members
private:
	int m_x;
	int m_y;
	int m_z;

This class CPoint3d is initialized through two kinds of the constructor. One constructor is a custom defined default constructor, which initializes all the data members of the CPoint3d class as zero. The other constructor takes all values required as a parameter. Both the constructors are shown below:

//Sample 02: Constructor
CPoint3d()
{
	m_x = 0;
	m_y = 0;
	m_z = 0;
}

//Sample 03: Constructor
CPoint3d(int px, int py, int pz)
{
	m_x = px;
	m_y = py;
	m_z = pz;
}

The class has a print method, which prints all the coordinate values on the screen. The function is shown below:

//Sample 04: Print Method
void Print(char * name)
{
	cout<<name<<endl;
	cout<<"X :" <<m_x <<endl;
	cout<<"Y :" <<m_y <<endl;
	cout<<"Z :" <<m_z <<endl;
	cout<<endl;
}

3. Overloading the Assignment Operator

The overloaded operator = shown in the below picture:

Assignment Operator

Source

In the above code, the left-hand side of the assignment calls overloaded = function. The right-hand side values are passed as the argument to the function. The implementation copies the values from the passed-in parameter to the calling object p1.

Note the check this == &rhs. This conditional check is useful to avoid the self-assignment. The keyword “this” gives the calling object’s address which nothing but the address of the left-hand side object. Since we received the parameter to the operator overloading as a reference, &rhs in our case gives the address of the right-hand side object. So, using this address-check we can avoid self-assignments. Returning the object is useful for making assignment as part of expressions as shown in the above picture. Below is the code (For copy paste)

//Sample 05: Overloading Assignment operator (Copy is between two objects)
CPoint3d& operator=(const CPoint3d& rhs)
{
	if (this == &rhs)
		return *this;
	else
	{
		m_x = rhs.m_x;
		m_y = rhs.m_y;
		m_z = rhs.m_z;
		return *this;
	}
}

4. Supporting const as RValue

The implementation given below shows handling the assignment for the constant values. In our case, the implementation supports constant values for integer. Say, for example, the below implementation makes the P2 = 73 possible. It assigns all the P1 coordinate values to 73.

//Sample 06: Overloading Assignment Operator (Copy is between Object and Constant
CPoint3d& operator=(const int all)
{
	m_x = m_y = m_z = all;
	return *this;
}

The entire class is shown below:
class CPoint3d
{
//Sample 01: Private Members
private:
	int m_x;
	int m_y;
	int m_z;

public:
	//Sample 02: Constructor
	CPoint3d()
	{
		m_x = 0;
		m_y = 0;
		m_z = 0;
	}

	//Sample 03: Constructor
	CPoint3d(int px, int py, int pz)
	{
		m_x = px;
		m_y = py;
		m_z = pz;
	}

	//Sample 04: Print Method
	void Print(char * name)
	{
		cout<<name<<endl;
		cout<<"X :" <<m_x <<endl;
		cout<<"Y :" <<m_y <<endl;
		cout<<"Z :" <<m_z <<endl;
		cout<<endl;
	}

	//Sample 05: Overloading Assignment operator (Copy is between two objects)
	CPoint3d& operator=(const CPoint3d& rhs)
	{
		if (this == &rhs)
			return *this;
		else
		{
			m_x = rhs.m_x;
			m_y = rhs.m_y;
			m_z = rhs.m_z;
			return *this;
		}
	}

	//Sample 06: Overloading Assignment Operator (Copy is between Object and Constant
	CPoint3d& operator=(const int all)
	{
		m_x = m_y = m_z = all;
		return *this;
	}
};

5. Testing the class

In the below example, First, we create two objects, one with values and other one pt2 with the default values of zero. Once both the objects are created, the content of the object pt1 is copied to the object pt2 using the assignment operator (=). As we have the overloaded operator, the copy occurs the way we define it.

//Sample 07: Basic Operation
CPoint3d pt1(10,20,30);
CPoint3d pt2;
pt1.Print("pt1");
pt2 = pt1;
pt1.Print("pt1");
pt2.Print("pt2");

In the next example, self-assignment and the multiple assignments are tested. Note that the conditional check against the “this” object with the address right-hand side avoids the self-assignment. In our example pt3 = pt3 tests the self-assignment and the statement pt1 = pt2 = pt3 tests the multi-assignment.

//Sample 08: Self and Multiple Assignment 
CPoint3d pt3(11,12,14);
pt3 = pt3;
pt1 = pt2 = pt3;
pt1.Print("pt1");
pt2.Print("pt2");
pt3.Print("pt3"); 

In the final example, the constant value is tested against the assignment operator. In our implementation, we further overloaded the assignment operator, which takes an integer as the parameter. That means the left side is actually an object, which invokes the assignment operator, and the right side is the integer literal value. Below is the code for it:

//Sample 09: Assignment of Constant value
CPoint3d pt4;
pt4 = 7;
pt4.Print("pt4");

Below is the output of executing the full code:

© 2013 sirama

Comments

    0 of 8192 characters used
    Post Comment

    • sirama profile image
      Author

      sirama 4 years ago

      I will write about that Govind.

    • Govind Rao profile image

      Govind Rao 4 years ago from Bangalore, India

      Hi its very nice explaintion ... i have one more question like

      what is the inline function , what is the difference between inline function and macro , please give me example ....

    • sirama profile image
      Author

      sirama 4 years ago

      Thanks Sonia.

    • soniarathod profile image

      Sonia Rathod 4 years ago from Framingham

      Its a really useful post..

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: "https://hubpages.com/privacy-policy#gdpr"

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)