Overloading Operators C++ Assignment Statement

In the C++programming language, the assignment operator, , is the operator used for assignment. Like most other operators in C++, it can be overloaded.

The copy assignment operator, often just called the "assignment operator", is a special case of assignment operator where the source (right-hand side) and destination (left-hand side) are of the same class type. It is one of the special member functions, which means that a default version of it is generated automatically by the compiler if the programmer does not declare one. The default version performs a memberwise copy, where each member is copied by its own copy assignment operator (which may also be programmer-declared or compiler-generated).

The copy assignment operator differs from the copy constructor in that it must clean up the data members of the assignment's target (and correctly handle self-assignment) whereas the copy constructor assigns values to uninitialized data members.[1] For example:

My_Arrayfirst;// initialization by default constructorMy_Arraysecond(first);// initialization by copy constructorMy_Arraythird=first;// Also initialization by copy constructorsecond=third;// assignment by copy assignment operator

Return value of overloaded assignment operator[edit]

The language permits an overloaded assignment operator to have an arbitrary return type (including ). However, the operator is usually defined to return a reference to the assignee. This is consistent with the behavior of assignment operator for built-in types (returning the assigned value) and allows for using the operator invocation as an expression, for instance in control statements or in chained assignment. Also, the C++ Standard Library requires this behavior for some user-supplied types.[2]

Overloading copy assignment operator[edit]

When deep copies of objects have to be made, exception safety should be taken into consideration. One way to achieve this when resource deallocation never fails is:

  1. Acquire new resources
  2. Release old resources
  3. Assign the new resources' handles to the object
classMy_Array{int*array;intcount;public:My_Array&operator=(constMy_Array&other){if(this!=&other)// protect against invalid self-assignment{// 1: allocate new memory and copy the elementsint*new_array=newint[other.count];std::copy(other.array,other.array+other.count,new_array);// 2: deallocate old memorydelete[]array;// 3: assign the new memory to the objectarray=new_array;count=other.count;}// by convention, always return *thisreturn*this;}// ...};

However, if a no-fail (no-throw) swap function is available for all the member subobjects and the class provides a copy constructor and destructor (which it should do according to the rule of three), the most straightforward way to implement copy assignment is as follows:[3]

public:voidswap(My_Array&other)// the swap member function (should never fail!){// swap all the members (and base subobject, if applicable) with otherusingstd::swap;// because of ADL the compiler will use // custom swap for members if it exists// falling back to std::swapswap(array,other.array);swap(count,other.count);}My_Array&operator=(My_Arrayother)// note: argument passed by value!{// swap this with otherswap(other);// by convention, always return *thisreturn*this;// other is destroyed, releasing the memory}

Assignment between different classes[edit]

C++ supports assignment between different classes, both via implicit copy constructor and assignment operator, if the destination instance class is the ancestor of the source instance class:

classAncestor{public:inta;};classDescendant:publicAncestor{public:intb;};intmain(){Descendantd;Ancestora(d);Ancestorb(d);a=d;return0;}

Copying from ancestor to descendant objects, which could leave descendant's fields uninitialized, is not permitted.

See also[edit]

References[edit]

External links[edit]

  1. ^Stroustrup, Bjarne (2000). The C++ Programming Language (3 ed.). Addison-Wesley. p. 244. ISBN 978-0-201-70073-2. 
  2. ^Working Draft, Standard for Programming Language C++, Section 17.6.3.1, Table 23; http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf
  3. ^Sutter, H.; Alexandrescu, A. (October 2004), C++ Coding Standards, Addison-Wesley, ISBN 0-321-11358-6 

Previous Page

Next Page


We already know the assignment operator in C++. In this tutorial we will be learning concept of C++ Overloading assignment operator.

Assignment operator in C++

  1. Assignment Operator is Used to assign value to an variable.
  2. Assignment operator is denoted by equal to sign.
  3. Assignment operator have Two values L-Value and R-value. Operator copies R-Value into L-Value.
  4. It is a binary operator.

C++ Overloading Assignment Operator

  1. C++ Overloading assignment operator can be done in object oriented programming.
  2. By overloading assignment operator, all values of one object (i.e instance variables) can be copied to another object.
  3. Assignment operator must be overloaded by a non-static member function only.
  4. If the overloading function for the assignment operator is not written in the class, the compiler generates the function to overload the assignment operator.

Syntax

Return_Type operator = (const Class_Name &)

Way of overloading Assignment Operator

#include<iostream> using namespace std; class Marks { private: int m1; int m2; public://Default constructor Marks(){ m1 =0; m2 =0;}// Parametrised constructor Marks(int i, int j){ m1 = i; m2 = j;}// Overloading of Assignment Operator void operator=(const Marks &M ){ m1 = M.m1; m2 = M.m2;} void Display(){ cout <<"Marks in 1st Subject:"<< m1; cout <<"Marks in 2nd Subject:"<< m2;}}; int main(){// Make two objects of class Marks Marks Mark1(45,89); Marks Mark2(36,59); cout <<" Marks of first student : "; Mark1.Display(); cout <<" Marks of Second student :"; Mark2.Display();// use assignment operator Mark1 = Mark2; cout <<" Mark in 1st Subject :"; Mark1.Display();return0;}

Explanation

private: int m1; int m2;

Here, in Class contains private Data Members m1 and m2.

Marks Mark1(45, 89); Marks Mark2(36, 59);

In the main function, we have made two objects ‘Mark1’ and ‘Mark2’ of class ‘Marks’. We have initialized values of two objects using parametrised constructor.

void operator=(const Marks &M ) { m1 = M.m1; m2 = M.m2; }

As shown in above code, we overload the assignment operator, Therefore, ‘Mark1=Mark2’ from main function will copy content of object ‘Mark2’ into ‘Mark1’.

Output

Marks of first student : Mark in 1st Subject : 45 Marks in 2nd Subject : 89 Marks of Second student : Mark in 1st Subject : 36 Marks in 2nd Subject : 59 Marks of First student : Mark in 1st Subject : 36 Marks in 2nd Subject : 59

Previous Page

Next Page


0 thoughts on “Overloading Operators C++ Assignment Statement

Leave a Reply

Your email address will not be published. Required fields are marked *