Something doesn't really make sense to me regarding custom type casting. The book I am reading over explains that a derived type can always be implicitly cast to a base type, while a base type must be explicitly cast to a derived type.
While I understand the concept, and it is easy enough to follow, I don't understand the logic behind this. It seems counter-intuitive to how the compiler works works with widening and narrowing casts. You can implicitly cast a short to an int, because the int holds at least as much as a short, but you must explicitly cast an int to a short because the int can hold more and you may lose data. With custom types, the derived type will hold at least as much data as the base type. For example, what if the derived type has additional fields added to it beyond what it inherited from its base type? You can implicitly cast it to the base type, so it could happen without you really being aware of it.
I am just not sure how to wrap my head around the logic here. Thanks!
I've been reading The Design and Evolution of C++, so can maybe shed some light on this...
Going from short to int does not risk data loss, whereas going from int to short does. As a result, short to int is automatic.
Now consider a mammal class that has two subclasses, dog and cat. Now consider the following code snippet:
Because the Mammal interface has all the necessary information to be certain that it won't access non-existent data in mycat, the assignment to animal is fine. However, Dog may add features that were NOT added to Cat (such as the growl() method and the AKCregistered bool flag). When you attempt to access those (non-existent) entities in mydog, there's no telling what might happen.Code:Cat* mycat = new Cat; Dog* mydog; Mammal* animal; animal = mycat; mydog = animal; //throws error... and well it should!
Ok, that makes sense. Thanks!
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks