Fr0stBit
Fr0stBit

Reputation: 1485

Find if object belongs to class in C++

I'm trying to make my own CBGE (Component Based Game Engine) in C++ but i am stuck at this question: How to i find if an Object belongs a specific class? Or equivalent with pointers, how do i find if an pointer points to an object of a specific class? Let me give an example:

I have this somewhere in my code:

//ComponentManager.h
...
std::map<rUUID, std::vector<Component*>> bucket;
...

where rUUID is a class that represents an UUID and Component is an abstract class that represents all type of components an Entity can have.

Now how can i get a specific type of Component (e.x. PositionComponent) for a given rUUID?

Also can somebody tell me if this type of design is good or bad practice and if so how should it be formed?

Upvotes: 0

Views: 2202

Answers (3)

If the class Foo has some virtual methods and if your compiler supports RTTI you could check dynamic_cast<Foo*>(p) != NULL to check if p points to some instance of Foo (assuming that p is declared as a pointerBar *p; to some super-class Bar of Foo)

Notice: dynamic_cast<Foo*>(p) != NULL will return true if p is pointing to an instance of some sub-class of Foo.

See also <typeinfo> header and typeid (as suggested by BlackMamba in another answer).

Upvotes: 1

BlackMamba
BlackMamba

Reputation: 10254

Maybe,you can use this function: typeid()

Upvotes: 1

Boris
Boris

Reputation: 622

RTTI works very well, but I want to show one more way.

As I see, all of your instances belong to the Component-class. In this case you can create your own virtual method inside of Component for your own use. Like this:

class Component
{
    virtual std::string
    type() const = 0;
};

class someComponent : public Component
{
    virtual std::string
    type() const { return "someComponent"; }
};

By this way you can get extra advantages. For instance, make the same types for completely different classes. Or, do more complex action than just return type. And your compiler doesn't have to have RTTI.

Upvotes: 1

Related Questions