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?
2 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.
class abc { public: abc(); ~abc(); abc& operator=(const abc& rhs) { if(&rhs == this) { // do never forget this if clause return *this; } // add copy code here } abc(const abc& rhs) { // add copy code here } }; Abc a, b; a = b; // rhs = right hand side = b So the operator is called on the object on the left hand side. But make sure you do not miss the if clause.
int = char;.