Polymoprhism downcast1/9/2023 ![]() The need for a downcast is, by the way, usually an indication of bad design. ![]() Still, there is runtime overhead needed to check whether your cast is actually safe (ie, distinguish the first case in the example from the second). Manager *Mng = dynamic_cast(ptr_to_employee) // will return nullptr ![]() You can do a safe downcast in C++ by using dynamic_cast: Manager *Mng = dynamic_cast(ptr_to_manager) // will return a pointer to the Manager object Or even Manager *Mng = (Manager*) new int // now, this is really bad.Īs a general rule, you should never use C-style casts in C++. For example, you might just as well do Manager *Mng = (Manager*) new Employee // not a good idea You're using a C-style cast (see ), which will, among casting away things such as const, happily cast any pointer to a Manager*. Vary depending on the "Employee" object (you are merely using one object typeīoth of your implementations do what you want them to, however the second one is very bad practice.įirst, let's clear up a misconception you seem to have: In your second implementation, you're not doing what is usually considered a downcast. Use any function that is type-specific, and so your runtime behaviour doesn't You don't use any Polymorphism in both examples. Then if you want to access the Designation later, you can do cout getDesignation() Virtual void setDesignation (const string & d) Īnd your function may look like: Employee* SomeFunction(bool SomeCondition) Virtual void setDesignation(const string & d) = 0 See theĪ better solution is to use virtual functions in order to avoidĬasting and make room to add more objects types beside "Manager".įor example, your header may look like: class Employee Not that safe all the time compared with upcasting), and if you have to In general you should avoid casting (especially the downcasting since it's You do downcasting in "Manager Mng = (Manager)Emp ". However, in Implementationġ, you do an implicit upcasting in "Emp = Mng ", while in Implementation 2 While both examples can improve, I think Implementation 1 is slightlyīetter. ** Comparing Implementation 1 and 2 / About dynamic casting So, I'm not sure what do mean by saying your examples work fine, For example: cout Designation() // error ! Initializing "Designation" while you will not be able to access it If you are indeed going to return "Employee" object why bothering Of type "Manager", while your define "SomeFunction(bool SomeCondition)" You are saying that you need to return a non-null object While I see some reasons behind your questions, I think you
0 Comments
Leave a Reply.AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |