Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check the type of derived class

Tags:

c++

In my program I have a class named Entity. Another class Invader inherits Entity. Since I want to have 4 different kinds of invaders, I declare classes Invader1, Invader2, Invader3 and Invader4 which inherit from Invader. Now I declare a Entity pointer type vector to store all Invaders like:

entities.push_back(new Invader4());
entities.push_back(new Invader3());
entities.push_back(new Invader2());
entities.push_back(new Invader1());
entities.push_back(new Invader0());

When I check the type of the element in entities at runtime, say

typeid(*entities->at(index)) 

It may return one of the 4 kinds of invaders. In entities there are also other objects which inherit Entity. So i just want to check if the type of the object is Invader or not, I don't want to know if it is Invader1, Invader2, etc.

How I can achieve this?

like image 906
Tony Avatar asked Dec 17 '22 00:12

Tony


1 Answers

There will be many ways to do this in C++, but the fundamental problem is that once you have to start querying elements in a container that is supposed to be polymorphic you might as well give up on the idea of using polimorphism. The whole point of having collections of polymorphic elements is that you can treat them all the same. So if you have a vector<Entity*> you should only treat its elements as Entity*s. If you find that you need to call some Invader-like functions on an Entity, then you are better off holding a container of Invader* too (using the same pointers as for the original container).

like image 146
juanchopanza Avatar answered Jan 03 '23 01:01

juanchopanza