Consider I am creating objects of two classes:
BaseClass B;
DerievedClass D;
and then i am doing:
B=D;
D=B;
Which is legal and why. This was a question asked by an interviewer of a C++ related Job. I know mostly B=D; will be valid (object slicing); but is it so that D=B; will only be valid if B has a default constructor? Yes, then why?
First line will always compile. The second line may or may not compile, as it entirely depends on how you have written each class. The rest of the answer will shed light on it. Read on.
No.
D=Bwill be valid only if D has definedoperator=which takesBas argument.Or if you do that in the initialization of
D, then it will valid only if a constructor ofDtakesBas argument.Or
Bhas defined a user-defined conversion toD.