This was an interview question. Consider the following:
struct A {};
struct B : A {};
A a;
B b;
a = b;
b = a;
Why does b = a; throw an error, while a = b; is perfectly fine?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Because the implicitly declared copy assignment operator of
Bhides the implicitly declared copy assignment operator ofA.So for the line
b = a, only the theoperator=ofBis a candidate. But its parameter has typeB const&, which cannot be initialized by anAargument (you would need a downcast). So you get an error.