Steini
Steini

Reputation: 2783

C++ Determine type of void* from two classes

I'm using wxWidgets and I have a search-function in my map-editor for my online game.

I search objects for different criteria and put these objects in the ComboBox list by their name and also add the object as reference data (void*),

I have an event onClickResult I want to mark and jump to the object which works but it crashes my application when switching between object types as it seems I cannot "reinterpret_cast" to determine the class objects which have no relation (no subclasses, two independent classes without any relation).

Question: Is there any way to determine what data-type is located in a void* (event.GetClientData() is returning void*) and cast it properly?

void SearchResultWindow::OnClickResult(wxCommandEvent& event) {
    Item* item = reinterpret_cast<Item*>(event.GetClientData());
    if (item) {
        this->selectRelatedMapItem(item);
    } else {
        Creature* creature = reinterpret_cast<Creature*>(event.GetClientData());
        if (creature) {
            this->selectRelatedMapCreature(creature);
        }
    }
}

Thanks!

Upvotes: 2

Views: 107

Answers (2)

acraig5075
acraig5075

Reputation: 10756

Don't add the object itself as the void* client data, but rather a pointer to a struct having sufficient members to lookup the object. For example some identifier to the container holding the object and an index into the container.

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234685

No there is no portable way of doing this in C++.

Once you cast to void* or const void* you are telling the compiler that you are going to keep track of the type yourself.

One solution here would be to have a base class from which all your objects inherit, and cast the void* to that type. From there, regular polymorphism can take over.

Upvotes: 5

Related Questions