Archived

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

Punx409

Inheritance - Arrays

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