quick yes or no question i hope

I have a class armor, weapon, and Item and in my code for checking the items I want to equip is Armor or weapon I have a call to

Armor* ar = dynamic_cast<Armor*> (Item[number]);

now I believe this is a pointer to the object Item[number] so then if it a armor piece I get the armor class stats. So if I delete the ar I delete the actual item??(this gives me a error anyways) is it fine to leave it as is for the next time someone tries to equip another piece of armor. it points to the new item in question. Or should I zero the pointer?
Last edited on
If Item is a sequence of 'Item *'s which each may be of a different derived type of Item, then the correct cast is dynamic_cast, not static_cast. If the object being pointed to is not an Armor but, say, a Weapon, ar == nullptr.
If you're certain that Item[number] points to an Armor, you can leave the static_cast and gain some performance benefits. Do note that if the pointer doesn't point to an Armor, using static_cast will result in undefined behavior (i.e. your program will likely crash).

To summarize:
* Use dynamic_cast to test the run time type information (RTTI) of the object.
* Use static_cast when you know that the object is of a certain run time type.
Last edited on
yeah I have a thing to detect whether its armor or weapon before hand im just wondering about the pointer. Thanks yes that shoulda been dynamic cast I somehow put static cast there, my check for a weapon type was dynamic

Last edited on
Oh, sorry, I misunderstood your question.

So if I delete the ar I delete the actual item?
Yes.

is it fine to leave it as is for the next time someone tries to equip another piece of armor.
You should zero the pointer.

By the way, you don't need to cast the pointer if all you'll do is delete it.
well at first I thought it was a new object, so I wanted to delete it but after I seen it was a pointer and remember something about removing pointers or zero'ing of something along that line. but thanks for the answer.
Topic archived. No new replies allowed.