1.

1 and 5 (or 5 and 1) as 1 + 9 = 10

Answer»

UPCASTING is converting a derived class reference or pointer to a base class. In other WORDS, upcasting allows us to treat a derived type as though it were its base type. It is always allowed for public inheritance, WITHOUT an explicit type cast. This is a result of the is-a relationship between the base and derived classes. Upcasting allows us to treat a derived type as though it were its base type.

When a derived class object is passed by value as a base class object, the specific behaviors of a derived class object are sliced off. We're left with a base class object. In other words, if we UPCAST (Upcasting and Down Casting) to an object instead of a pointer or reference, the object is sliced. As a result, all that remains is the sub object that corresponds to the destination type of our cast and which is only a part of the actual derived class.

Converting a base-class pointer (reference) to a derived-class pointer (reference) is called downcasting. Downcasting is not allowed without an explicit TYPECAST. The reason for this restriction is that the is-a relationship is not, in most of the cases, symmetric. A derived class could add new data members, and the class member functions that used these data members wouldn't apply to the base class.

//Example of upcasting and downcasting:

class Parent { public:  void sleep() {} }; class Child: public Parent { public:  void gotoSchool(){} }; int main( ) {  Parent parent;  Child child;  // upcast - implicit type cast allowed  Parent *pParent = &child;  // downcast - explicit type case required  Child *pChild =  (Child *) &parent;  pParent -> sleep();  pChild -> gotoSchool();  return 0; }


Discussion

No Comment Found