Bank of America Interview Question
Country: India
C++ supports up-casting i.e. assigning the derived class object's address to base class pointer. The opposite of that , i.e. down-casting is not possible. Because the size of derived class object is always greater than or equal to that of base class, and so if any pointer arithmetic would cause unexpected results.
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. so if base class doesn't know anything about child class then how he behave like child class.
Can we use downCasting here ? . Converting a base-class pointer (reference) to a derived-class pointer (reference) is called downcasting. Downcasting is not allowed without an explicit type cast.The downcasting in the above line can lead to an unsafe operation.C++ provides a special explicit cast called dynamic_cast that performs this conversion
- Rohit Hajare March 28, 2016Base * b = new Base();
derived * d = dynamic_cast<derived * >(b);