Note that there are some explanatory texts on larger screens.

plurals
  1. POObject type detection in hierarchy
    primarykey
    data
    text
    <p>I've got a hierarchy of game objects:</p> <pre><code>class GameObject { public: virtual void update(float dt) = 0; virtual void draw() = 0; }; class Building : public GameObject {} class Sawmill : public Building {} class Human : public GameObject {} </code></pre> <p>and so on. All objects are managed by the game (which is not a subclass of GameObject :). The game stores all the objects in std::vector&lt;GameObject *&gt; and successfully invokes virtual methods such as update and draw, that's all good. But sometimes I need to detect what type of GameObject I'm dealing with. For this case we've came up with a solution: GameObject has a enum of GameObject types and each GameObject subclass returns his own value from this enum.</p> <pre><code>class GameObject { public: enum GOType { GOGameObject, GOBuilding, GOSawmill, GOHuman, ... } static GOType Type() { return GOGameObject; } virtual GOType getType() const { return GameObject::Type(); } }; class Building : public GameObject { public: static GOType Type() { return GOBuilding; } virtual GOType getType() const { return Building::Type(); } }; </code></pre> <p>So, every subclass of GameObject has it's own version of "static GOType Type()" method which returns a value from enum GOType. And it has overloaded virtual method "GOType getType() const" which just calls it's own class method Type(). Anywhere in game I can check if the object I have a pointer to is, for example, a Building:</p> <pre><code>if (obj &amp;&amp; obj-&gt;getType() == Building::Type()) { // then do stuff } </code></pre> <p>To make it clear - this solution works fine and has proven itself to be extensible and very efficient (the first solution we've came up with was returning strings in getType() and comparing them; it was veeery slow). </p> <p>The only downside I see is that I have to extend GOType in GameObject every time I add a new GameObject subclass. Now it contains about a hundred of types and it doesn't look and feel beautiful (I'm beeing a perfectionist here :)</p> <p>So, my question is: is there any other solution of the problem which is as efficient as this one but without necessity of extending GOType in GameObject?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload