Jump to content
  • Advertisement


This topic is now archived and is closed to further replies.


Inheritance - Arrays

This topic is 5921 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

I have two classes, ''ITEM'' and ''WEAPON'' which inherits from ITEM. Is it possible to have an array of type ITEM that can hold the inherited WEAPON. I was thinking because WEAPON ''is an'' ITEM it would work but it doesn''t. Is there a way?

Share this post

Link to post
Share on other sites
Doing this doesn''t work properly because a C++ array can only hold items of one type. Putting a weapon into an item array causes the weapon object to be "sliced", leaving just the bits derived from item. Obviously that isn''t usually what you want.

If you need to hold a collection of objects of different types (all derived from item) you can use an array of "item *". To do that, you create the objects on the heap (with new) and put their address in the array. When you are done with them you need to take the pointer out of the array, remebering to delete the object so you don''t have a memory leak.

The next thing to sort out is how you use the objects now that you don''t know their exact type. You can use polymorphism if the objects all support the same functions but in different ways. If weapon has extra functionality over item, you''ll need to determine the actual type of the pointed-to object before you can use it.

Share this post

Link to post
Share on other sites

  • Advertisement

Important Information

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

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!