I have a class Item, and there are two classes derived from it Sword and Shield.
I want my player to have an array of items:
class Item
{
int x;
};
class Sword : public Item
{
int sharpness = 10;
};
class Shield : public Item
{
int blockChance = 2;
};
class player
{
Item* items[4];
player()
{
items[0] = new Sword;
items[1] = new Sword;
items[2] = new Shield;
items[3] = new Shield;
}
};
Is there a way I can access values of Sword or Shield from items, for example:
items[2]->blockChance;
without having a separate array of Swords and Shields
If this is not possible, then I would just have a separate array of each, but a single array containing both would make this much easier
In order to access the properties of a derived class via the base class, you can add a virtual method. This is a method a derived class can override to provide a different implementation. If the base class has no meaningful implementation for it, it can also be abstract (AKA pure-virtual), which will force the derived class to implement it.
There are several other issues you should be aware of:
When dealing with inheritance and virtuals method, it is important to have a virtual destructor in the base class. Otherwise the destructor of the derived classed will not be invoked when they are access via a pointer/reference (even if in your toy example this is not relevant, it's a good practice).
Instead of using raw C arrays, you should favor
std::arrayfor static sized arrays, andstd::vectorfor dynamic sized ones.Instead of using raw pointers with manual
new/delete, you should use smart pointers:std::unique_ptr(the default), orstd::shared_ptr(if shared ownership is required).You can use a member initialization list to init
itemsin the constructor of classPlayer.The complete solution is demonstrated below:
Output:
Live demo - Godbolt