Overriding Virtual Functions

In reply to haithamx15:
Dave, please correct me If I’m wrong. And I have another question. I still don’t grasp why would we need cast for? is there a practical example that shows the significance of it? I thoroughly watched your video of OOP and I understood it preciesly but wasn’t able to think of a case where we need it.

A derived class is an extension of base class. So, a base class variable can point to derived class object without any problems. We can’t say the same thing about if we go vice versa. This should not be allowed. But what happens when base class variable actually contains derived class.

BaseC B1 ;
DerivedC D1 ;
BaseC general_class_handle;

D1 = new();
general_class_handle = D1; // this is legal as general_class_variable is of base class type and pointing to derived class object
D1 = general_class_handle; // this is not legal, in the current form, as we are trying to assign a base class object to derived class variable. However, we know that general_class_handle actually points to derived class. Hence casting is needed so that compiler can ascertain

It is very important to note that all this is not necessary if these checks can be done at compile time but it is not. The above assignments are happening at run time. So, additional checks are necessary …