Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 205
Kerry Avatar asked Nov 17 '25 06:11

Kerry


1 Answers

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.

like image 70
Luchian Grigore Avatar answered Nov 19 '25 20:11

Luchian Grigore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!