3

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?

3
  • You mean "assignment operator", right? Commented Jan 8, 2012 at 14:18
  • Assignment only makes sense for objects, not for types. It's like asking for int = char;. Commented Jan 8, 2012 at 14:20
  • @KerrekSB I'm assuming he wants the assignment between objects, not types, but that's a good point. Commented Jan 8, 2012 at 14:23

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Therefore I assume the syntax should be something on the lines: A& A::operator=(const B& from)
You assumed right that what i want is A a;B b; a = b; Thanks for the answer :)
0
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.