6/3/2023 0 Comments Upcast vs downcast![]() ![]() Downcasting To Reach Members A superclass with many subclasses. But C++ does provide syntax for downcasting, suggesting that it is sometimes needed although it is potentially dangerous. Memory is never blank or empty - it always contains some random bit pattern - but the contents are unrelated to an Employee object and don't have any meaning when accessed in this way. Changing an object into a different one allows the compiler to "locate" data that is not there. The potential problem with downcasting is that it may turn an object into something it is not. However, being an Employee pointer, it also allows the compiler to access the Employee members, which were never created because the program instantiated a Person object! Attempting to use the phantom members will produce unpredictable and completely incorrect results. ![]() The variable cto is a pointer to an Employee, which allows the compiler to access the Person members, which is completely safe. The statement instantiates a Person (superclass) object but downcasts it to an Employee (subclass) object.
0 Comments
Leave a Reply. |