o_yeah
o_yeah

Reputation: 788

Copy assignment operator= is not called

Why overloaded operator (operator=, specifically) is not called in this case?

#include<iostream>
using namespace std;

class mc{
    public:
        mc()=default;
        mc(mc& that){cout<<1;} //simplified copy constructor
        mc& operator=(mc& that){cout<<2; return that;} // simplified copy assignment operator
        mc operator=(mc that){cout<<2; return that;}   // another simplified copy assignment operator
};

int main(){
    mc i;       //call default constructor
    mc j = i;   //Why this line calls j's copy constructor? 
                //It used "=" symbol, how come copy assignment operator (operator=) is not called? 
}

Upvotes: 2

Views: 501

Answers (1)

Ahmed Anter
Ahmed Anter

Reputation: 650

The main rule is:

Copy constructor is used when creating a new object.

Assignment operator is used if the value of an existing object to be changed.

difference between copy constructor and assignment operator

Upvotes: 3

Related Questions