
Patrick B. answered 10/15/20
Math and computer tutor/teacher
The main rule of thumb here is that the child CAN be assigned to the PARENT, but not vice versa.
class Sandwich
{
public :
Sandwich()
{
}
};
class Sub : public Sandwich
{
public :
Sub()
{
}
};
int main()
{
// option A : properly declares and initializes pointers to the Sandwhich and Sub objects
Sandwich * x = new Sandwich();
Sub * y = new Sub();
// option A is correct and legal
//option B: both pointers point at the sub
x = y;
// option B is correct and legal; Child can be assigned to parent
// y=x; //COMPILER ERROR: cannot assign parent to child opton C is ILLEGAL !!!
// y = new Sandwich(); //COMMPILER ERROR: child object pointer cannot contain address of parent object
// option D is ILLEGAL !!!
x = new Sub(); // Address of child can be asigned to pointer to Parent;
// option E is legal
*x = *y; // child object can be assigned to parent object; option F is legal
*y = *x; // COMPILER ERROR: cannot assign parent to child
// option G is ILLEGAL !!!
}