Advertisement

Inheritance - Arrays

Started by May 06, 2002 10:24 AM
0 comments, last by Punx409 22 years, 7 months ago
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?
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.

This topic is closed to new replies.

Advertisement