Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ assignment operator, can we replace it with copy?

When I was reading:

What's the difference between assignment operator and copy constructor?

here: What's the difference between assignment operator and copy constructor?

The following example was shown:

A aa;
A a = aa;  //copy constructor

vs:

A aa;
A a;
a = aa;  // assignment operator

and my question is, why we need the assignment operator at all? I mean that it will be more efficient to use the copy constructor in this case while it does the same job.

could someone give a real-world example of the use of assignment operator where that can't be replaced by the copy constructor?


1 Answers

You need assignments when you want to change a value after it has already been constructed. For example:

  • change a value that is already stored in a std::map
  • change the nth value inside a std::vector
  • change the value of a variable outside a loop
  • change the value of an output parameter provided as a pointer or reference
  • ...

The list could really go on almost endlessly. But in your example it is true that one could simply avoid the use of an assignment.

like image 128
Jan Schultke Avatar answered Oct 26 '25 06:10

Jan Schultke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!