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

Overloading Assignment Operator =, C++ Example

Updated on June 14, 2016
sirama profile image

I am a software engineer. I have been come across C++,MFC, .net technologies. 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 3 years ago

      I will write about that Govind.

    • Govind Rao profile image

      Govind Rao 3 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.