Home > database >  Why one statement calls copy constructor while the other one call calls copy-assignment operator?
Why one statement calls copy constructor while the other one call calls copy-assignment operator?

Time:02-22

#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?

CodePudding user response:

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.

  •  Tags:  
  • c
  • Related