Sunday, 22 March 2015

Overloading of operator= in C++ with example

Overloading of operator= in C++ with example:

The operator= is confidentially connected to the object on the left side of the ‘=’.
If it was possible to define operator= globally, then you might attempt to redefine the built-in ‘=’ sign:
See the below syntax
int operator=(int, Ourowntype); 

When we create the operator= in our code, we need to copy all the required data from,
Right hand side object into the current object left hand side object to perform whatever
we consider “assignment” for your class.
Let us see the sample example that works on operator=

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>

using namespace std;
class TestAssignOperator
int iFirstVal, iSecondVal;
float fThirdVal;

TestAssignOperator (int iVal1 = 0, int iVal2 = 0, float fVal3 = 0.0) : iFirstVal(iVal1), iSecondVal(iVal2), fThirdVal(fVal3)


TestAssignOperator& operator=(const TestAssignOperator& ocRetObj) {

iFirstVal = ocRetObj.iFirstVal;

iSecondVal = ocRetObj.iSecondVal;

fThirdVal = ocRetObj.fThirdVal;

return *this;


friend ostream&

operator<<(ostream& os, const TestAssignOperator& ocRetObj)

  { return os << "iFirstVal = " << ocRetObj.iFirstVal << ", iSecondVal = " << ocRetObj.iSecondVal << ", fThirdVal = " << ocRetObj.fThirdVal; }


int main ()


TestAssignOperator iFirstVal, iSecondVal(1, 2, 3.3);

cout << "iFirstVal: " << iFirstVal << endl;

cout << "iSecondVal: " << iSecondVal << endl;

iFirstVal = iSecondVal;

cout << "iFirstVal after assignment: " << iFirstVal << endl;

  getchar ();

  return 0;


The output of the above program is
iFirstVal: iFirstVal = 0, iSecondVal = 0, fThirdVal = 0

iSecondVal: iFirstVal = 1, iSecondVal = 2, fThirdVal = 3.3

iFirstVal after assignment: iFirstVal = 1, iSecondVal = 2, fThirdVal = 3.3

Here, the object on the left hand side of the = copies all the elements of the object on the right hand side, i.e iSecondVal  to iFirstVal. Then returns a reference to itself, which allows a more complex expression to be created.

NOTE: Before assigning two objects of the same type, we should always check first for self-assignment: is the object being assigned to itself? In some cases, such as this one, it’s harmless if you perform the assignment operations anyway, but if changes are made to the implementation of the class, it can make a difference, otherwise it is very difficult to find the bugs caused by the assignment operator.

No comments: