Say I have an Animal class, it would be nice to be able to tell that a pointer is pointing to an Animal object. I know in C++ RTTI and dynamic casting (I think they're the same thing?) is used to find out what type a reference or pointer is. But it's only available through polymorphic inheritance. So if I want a class to be able to tell me what type it is, I have to declare:
virtual void dummyfunc(){}
And dynamic casting and RTTI would work fine with it. But I can't for example have a void pointer pointing to something, and be able to tell what type it's pointing to. For example:
Animal dog;
Animal* animalPtr = &dog;
typeid(*animalPtr).name(); // RTTI works fine
dynamic_cast<Animal*>(animalPtr); // Dynamic cast tells me if it's an Animal. Well technically the compiler knows at compile time, but just as example.
void* voidPtr = &dog;
typeid(*voidPtr).name(); // Error, typeid expression must be a complete type
dynamic_cast<Animal*>(voidPtr); // Error, same thing
I kind of understand the reasons why the language won't let me do this from void pointers.
The simplest way I know how to make a class tell me what type it is is to just include a virtual dummy function. Is it just me or does this seem to be a hacky way to do it? For example I've thought about having a struct Dummy{} with a virtual function just for the hell of it, and have every object in my program inherit from that. Then any reference to an object would be a reference to Dummy class, and I would be able to tell exactly what type the object was. So for example:
Dummy* listOfGodKnowsWhat[1000]; // Assign them to anything
// Loop through, if typeid matches what I want, do the right thing
I'm thinking that this is really flexible, but I guess if I want a fully dynamic system then I shouldn't be using C++. Is that the easiest way to be able to tell the type, just add a virtual function? Is this what reflection is? When every object knows what type it is?
Edit: Thanks to latedeveloper for mentioning that I only need a virtual destructor, no need for anything dummy.