How can I swap a parent pointer and a child pointer in c++?

  c++, casting, inheritance, instanceof, polymorphism

Weapon inherits from Item.

weapon is a member of class Hero. I want to swap it with the item passed in the function, which is also a Weapon for this example (I’ll add more cases).

void Hero::equip(Item* item){
    
    if(instanceof<Weapon>(item)){std::swap (item, static_cast<Item>(weapon));}
}

Basically, when something is equipped from the hero’s inventory, I want it to get stored in the corresponding member of the Hero, and the item that was previously equipped to get stored back in the inventory, no matter the type of item. The inventory is a std::vector<Item*> so it can hold polymorphic items.

Upcasting weapon doesn’t seem to be working, because Item is virtual. Every other type of casting I tried also failed, and so did some attempts to manually swap them. If you’re wondering about instanceof, I copied this template so I can use it in C++:

template<typename Base, typename T> 
inline bool instanceof(const T *ptr) {
    return dynamic_cast<const Base*>(ptr) != nullptr;
}

When I use Item* instead of Item, I get:

no matching function for call to ‘swap(Item*&, Item*)’

Source: Windows Questions C++

LEAVE A COMMENT