At the present moment I am reading C++ 11 standard, in which (chapter 12)
among special member functions is mentioned ?copy? assignment operator.
I have already faced with operator=, which is simply assignment operator
My first guess was that it is used in statements like this:
Class_name instance_name1 = instance_name2;
when an object is created and initialized simultaneously, I checked my assumption and got that this done by means of copy constructor(which was expected).
So, what for copy assignment operator is used, how to declare it and can you give me some example of its usage.
Thanks in advance!
It’s defined in the standard, 12.8/17:
So for example:
Assignment operators are used when you assign to an object. You might think that doesn’t say much, but your example code
Class_name instance_name1 = instance_name2;doesn’t assign to an object, it initializes one. The difference is in the grammar of the language: in both cases the=symbol precedes something called an initializer-clause, butClass_name instance_name1 = instance_name2;is a definition, whereasinstance_name1 = instance_name2;on its own afterinstance_name1has been defined is an expression-statement containing an assignment-expression. Assignment-expressions use assignment operators, definitions use constructors.If the usual rules for overload resolution select an assignment operator that is a copy assignment operator, then that’s when a copy assignment operator is used:
The reason there’s a distinction between copy and non-copy assignment operators, is that if you declare a copy assignment operator, that suppresses the default copy assignment operator. If you declare any non-copy assignment operators, they don’t suppress the default copy assignment.