2
#include<bits/stdc++.h>
using namespace std;


class numbered{
    public:
        int value;
        numbered(){}
        numbered& operator= (const numbered& n){
            this->value=n.value+1;
            return *this;
        }
        numbered (const numbered& n){
            this->value=n.value+2;
        }
};


int main(void){
    numbered n1;
    n1.value=15;
    numbered n2=n1;
    numbered n3;
    n3=n1;
    cout << n2.value <<endl;
    cout << n3.value <<endl;

    return 0;
}

Above this code segment, why does numbered n2=n1 call copy constructor while numbered3 n3;n3=n1; calls copy-assignment operator. Both of two variables, n2 and n3, are assigned by =. So what is the difference between two of them?

Virux
  • 138
  • 9
  • 2
    `numbered n2=n1;` is initiailzation while `n3=n1;` is assignment. – Jason Feb 22 '22 at 05:46
  • @Anoop Rana Is that mean copy constructor works in initialization while copy-assignment operator works in assignment expression? – Virux Feb 22 '22 at 05:52
  • 1
    Basically yes as explained in my answer below. More details can be found at the links given in my answer. – Jason Feb 22 '22 at 05:53
  • https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h – Karl Knechtel Feb 22 '22 at 05:59
  • 1
    "Both of two variables, n2 and n3, are assigned by =. " No, they aren't. Just because the code says `=`, doesn't mean it's an assignment. – Karl Knechtel Feb 22 '22 at 06:01
  • 1
    [Why should I not `#include `?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) [Why is `using namespace std;` considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Evg Feb 22 '22 at 06:08

1 Answers1

2

Statement 1

When you wrote:

numbered n2 = n1; //this is initialization and so this uses copy constructor

The above statement is initialization of variable n2 using variable n1. And from copy constructor's documentation:

The copy constructor is called whenever an object is initialized (by direct-initialization or copy-initialization) from another object of the same type...

Since in this case we are doing initialization so according to the above quoted statement, this will use copy constructor.

Statement 2

On the other hand, when you wrote:

n3=n1; //this is assignment expression and so this uses copy assignment operator

The above statement is an assignment of n1 to n3. And from copy assignment operator's documentation:

The copy assignment operator is called whenever selected by overload resolution, e.g. when an object appears on the left side of an assignment expression.

Since the object n3 appears on the left side of the assignment expression, therefore according to the quoted statement above, this uses copy assignment operator.

Jason
  • 36,170
  • 5
  • 26
  • 60