- Assignment operator in C++
––The
assignment operator inC++ programming language is '='. Like other operators in C++, it can be overloaded.The copy assignment operator is a special case of assignment operator used to assign objects of the same class to each other. It is one of the
special member functions , and is generated automatically by thecompiler if not explicitly declared by the programmer. The compiler-generated code performs ashallow copy .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. [cite book
last = Stroustrup
first = Bjarne
authorlink = Bjarne Stroustrup
title = The C++ Programming Language
edition = 3
publisher = Addison-Wesley
date = 2000
isbn = 978-0201700732
ref = stroustrup
pages = 244 ] For example:Overloading copy assignment operator
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:# Acquire new resources
# Release old resources
# Assign the new resources' handles to the objectHowever, if no-fail swap method is available for all the members 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 [Citation
last1 = Sutter | first1 = H. | author1-link = Herb Sutter
last2 = Alexandrescu | first2 = A. | author2-link = Andrei Alexandrescu
title = C++ Coding Standards
publisher =Addison-Wesley
date = October 2004
year = 2004
isbn = 0-321-11358-6 ] :The reason why operator = returns
My_Array&
instead ofvoid
is simple. It allows for concatenation of assignments like this:ee also
*
Operator overloading
*Operators in C and C++ References
–
Wikimedia Foundation. 2010.