Jump to content
  • Advertisement
Sign in to follow this  
RebNyx

How can inheritance benefit me?

This topic is 3697 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

This is my first attempt at inheritance, and I am also beginner of the C++ language. In a small game-engine I'm working on... I'm storing items in an array. EX: Item itemlist[Max_Items] Now, what if I want to use inheritance.. and make Weapon, Armor, Key, Potion classes which derive from the Item class. I'm wondering, in this situation how can inheritance help me? Does the way items are being stored, need to be changed?

Share this post


Link to post
Share on other sites
Advertisement
Quote:
Original post by RebNyx
Item itemlist[Max_Items]

C++ has better containers than arrays, without those arbitrary size limits. Use a std::vector.
std::vector<Item> items;


Quote:
Original post by RebNyx
Now, what if I want to use inheritance.. Does the way items are being stored, need to be changed?

Yes. You can't use arrays or vectors of things polymorphically, because the objects will get sliced when you store them. You must use pointers instead.

std::vector<Item*> items;
items.push_back(new Sword(foo, bar));
items.push_back(new Potion(baz));

Don't forget to delete the newed items when you're done with them.
while (!items.empty())
{
delete items.back(); // delete the item itself
items.pop_back(); // remove the pointer from the vector
}

Alternatively, you can let std::vector<boost::shared_ptr<Item> > handle the memory management.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!