Thursday, July 9, 2009

Inheritance with C++ (type casting)?

I've got a class called Item, and two class that inherit it (Weapon and Armor). I've got a separate class containing two variables, Armor armor and Item slot, and I'm creating a method in which it takes the Item from slot and puts it in Armor. I've got some if statements that prove this is an Armor type, so how can I do this?





I've tried armor = (Armor)slot; but it says that it can't cast it like that. Anyone have any suggestions or ideas? Thanks =)

Inheritance with C++ (type casting)?
Usually when you cast something using inheritance, you have to declare it using the :: notation... Have you already done this when you instantiated it? If you haven't, your problem may lie there. Also, I myself have been working on an RPG style game using C++, I find that it's easier to put those slots in the classes for weapons/armor and then just use a database file to fill in and create those items on compile time. Also, since you're using classes, you aren't REQUIRED to use all the private variables, so you could just make a SINGLE class called Equipable and then have smaller classes such as weapons, armor, etc and have them inherit the Equipable class (so all the common variables and functions are available to all inherited classes WITHOUT rewriting the separate functions for each type)
Reply:I would suggest that your third class, lets call it Container has two variables:


Armor *armor;


Item *slot;








I think you'd have an easier time with your cast
Reply:It's been awhile since I've done C/C++, but maybe try mallocing before casting? Or maybe armor = new Armor(slot)?


No comments:

Post a Comment