How do I check the type of an object?

PLEASE HELP!!!!!!!!!!!!!!!!!!!!!!

I have a class called Item.
I have 2 other classes that publicly inherit from Item class:
- Weapon
- Armor

I also have a Player class.
Inside the Player class, I have an array of pointers of Items, and a pointer to a weapon:

Item** inventory = new Item*[10];
// This is a pointer to an array that holds pointers of Item objects
Weapon* weapon;
//This is a pointer to a Weapon object


Finally, I wrote the following function in the Player class:
void Player :: func( int index )
{
weapon = inventory[index];
}

I'm trying to make the weapon pointer point to an Item, but it can't, even
though Weapon is a specific type of Item.

My question:
Can I check the type of an object? Can I ask the compiler:
"Which type of Item is inventory[index]? Is it a weapon or an armor?


PLEASE HELP!!!
Thanks in advance!
why using pointer to pointer . ..
Item** inventory = new Item*[10];
A simple solution would be -> weapon = dynamic_cast<Weapon *>(inventory[index]);

If inventory[index] is a Weapon pointer, you'll get it. Otherwise, weapon will be zero.

Another way to do it would be to use virtual functions -> http://codepad.org/fJGw5iuF

EDIT:

I forgot that in order to be able use dynamic_cast you must have at least
one virtual function in your base class. A good choice is the destructor:

1
2
3
4
5
6
7
8
class Item
{
    //...

public:

    virtual ~Item() {}
};
Last edited on
I'm trying to make the weapon pointer point to an Item, but it can't, even though Weapon is a specific type of Item.


Note that the following assumes public inheritance.

It can't, because a weapon is a specific type of item. How do we know a weapon is a kind of item? Because everything you can do to an item (i.e. all functions and members), you can do to a weapon.

Weapon inherits from item. Thus, all weapons are also items. Are all items weapons? No. Some could be players, some could be plain items, some could be something else. Are we sure? Well, there are things you can do to a weapon (i.e. all functions and members) that you cannot do to an item - the extra things weapon has alongside the inherited parts. So clearly items are not weapons.

If you have a weapon pointer, it must point at something that is a weapon. Is a weapon a weapon? Yes. So it can point at a weapon. Is an item a weapon? No, as discussed above. So a weapon pointer can only point at a weapon.

If you have an item pointer, it must point at an item. Is a weapon an item? Yes, as discussed above. Is an item an item? Yes. Is a player an item? Yes. So the item pointer can point at all of these.

The key point is that all items are not weapons, so you cannot make a weapon pointer point at an item.
Last edited on
Topic archived. No new replies allowed.