c++copy-constructorassignment-operator

When assigning A=B, does this call A's or B's assignment operator?


If I have two classes A and B and I do A=B which assignment constructor is called? The one from class A or the one from class B?


Solution

  • There's copy constructor and there's assignment operator. Since A != B, the copy assignment operator will be called.

    Short answer: operator = from class A, since you're assigning to class A.

    Long answer:

    A=B will not work, since A and B are class types.

    You probably mean:

    A a;
    B b;
    a = b;
    

    In which case, operator = for class A will be called.

    class A
    {
    /*...*/
       A& operator = (const B& b);
    };
    

    The conversion constructor will be called for the following case:

    B b;
    A a(b);
    
    //or
    
    B b;
    A a = b; //note that conversion constructor will be called here
    

    where A is defined as:

    class A
    {
    /*...*/
        A(const B& b); //conversion constructor
    };
    

    Note that this introduces implicit casting between B and A. If you don't want that, you can declare the conversion constructor as explicit.