2

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? 
}
o_yeah
  • 688
  • 7
  • 17
  • 2
    Not all that contains `=` is an assignment. `mc j = i;` is not an assignment, it's an initialization. It uses the copy constructor. – Igor Tandetnik Nov 01 '20 at 19:14
  • @IgorTandetnik Thanks. I got your point. But I'm still confused about how the compiler handles this case. When it sees a `=` in the `main`, the first thing to do is to look for an `operator=` function to call on. Isn't that correct? – o_yeah Nov 01 '20 at 19:23
  • 1
    That isn't correct. `type var=init;` declares a variable named `var` of type `type`, and initializes it with the expression `init`; this is not an assignment, and never uses `operator=`. `var = value;` performs an assignment of `value` to the variable. It's not as simple as "look for equal sign". There are other places in C++ syntax where an equal sign doesn't mean assignment - e.g. default argument: `void f(int x = 42);` – Igor Tandetnik Nov 01 '20 at 19:24

1 Answers1

3

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

Ahmed Anter
  • 650
  • 4
  • 13
  • Thanks. I got your point. But I want to look deeper into how the compiler handles this case. When it sees a = in the main, the first thing to do is to look for an operator= function to call on. Is that correct? – o_yeah Nov 01 '20 at 19:32
  • 1
    the first thing the compiler check for var declaration like int i; and allocates the required memory for that object then it calls the appropriate constructor. but when it sees the var i=k; then instead of calling constructor and then assignement operator it calls the copy constructor directly – Ahmed Anter Nov 01 '20 at 19:37