D
D
Dima Gashko2018-09-21 21:35:26
OOP
Dima Gashko, 2018-09-21 21:35:26

Is there any way to find out if an object belongs to a class in c++?

I have (not yet but before I get started I need to sort things out) an array of game objects. These are different classes that inherit from one (Object, for example). That is, they are all Object.
But how do I understand that an element of this array is not only an Object in general, but also, for example, a player or an enemy or a wall or something else?
In js I would write:
if (objects[i] instanceof Wall) { ... }
But how to do this with C++? And without crutches.
Or maybe I do not understand correctly how such things are done in C ++? If yes, how is it organized?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaly, 2018-09-21
@vt4a2h

Why do you need this? There is polymorphism, and castes are bad style almost always.
You can use a lot of things, including tags. In the base class, you create an enum, where each element is the type of the descendant + 1 element per type of the base class. In the base class, you define a virtual method like type() and implement it for all descendants.
But before you do this, think carefully about whether you need it. Read about SOLID, especially about the letter L.

G
GavriKos, 2018-09-21
@GavriKos

Read this for example:
https://stackoverflow.com/questions/1986418/typeid...
especially the answer.
Somewhere I saw another implementation through templates.
But 90% something is wrong with the architecture if this is necessary. And if you really need to and inherit from the base class, then make a method in the base class that will return the type by enum.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question