Google News
logo
CPP - Interview Questions
What is upcasting and downcasting in C++ and What is object slicing in case of upcasting?
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.
Advertisement