I am currently working on a Component based game engine written in c++. All components inherit from a component base class. All components in the scene are upcasted into a vector of Components were they can be iterated over and Update() and such can be called.
I am trying to come up with a communication system for the components. If I have a function called GetComponent<Type>() Like Unity will I be able to return a component from what is used to be before it was upcasted.
So basically i have an upcasted component and I want to reverse it so it is its original class and then return it via the function(as the class it used to be). Is this possible? If it were possible how would the component know what class it used to be?
Are there any examples of doing this I can learn from?
For this to work you would have to know the original type of the component as it was before adding it to the collection (upcasting it).
So knowing that, it can be done like this (assuming
componentis of typeComponent*):Not that dynamic_cast can fail => the above can set
specifictonullptrif the actual component type is not applicable. That, and the fact that it is slower than the other casts make it the most disliked of the C++ casts.You can also take a look at boost::polymorphic_downcast, which is similar in function. It makes a
dynamic_castand asserts if it fails in DEBUG mode, but does the fasterstatic_castin RELEASE mode.