How to make a class array with sub classes and access elements

Hello,
I want to make something like this, but I don’t know how to do this in C++:

class Item
{
public:
    int price;
 };

class Ball : Item { };

Item items[1];

items[0] = Ball();
items[0].price = 100;

Thanks in advance!

1 Like

Have you tried running that?

The code is almost exactly the same.

class Item
{
public:
    int price;
 };

class Ball : public Item { };

// Global variable
// The default consturctor is called automatically for globals
Item items[1];

int main(void)
{
  items[0].price = 100;
  return 0;
}

The reason for public:

  • If the inheritance is public, everything that is aware of the base class and the child class is also aware that the child class inherits from the base class
  • If the inheritance is protected, only the child class, and its children, are aware that they inherit from the base class.
  • If the inheritance is private, no one other than the child class is aware of the inheritance.

And class causes inheritance to be private by default, hence it needs to be manually made public in this case.

(Taken from this SO answer.)

1 Like

Also you need to use pointers (c-style or smart ones like std::shared_ptr or std::unique_ptr depending on your use), with virtual methods for every things you might call as Item, but implemented in its derived classes such as Ball.

That’s because the size of an Item might vary depending on the derived class.

That gives you something like that:

std::shared_ptr<Item> items[1];
1 Like

A little late to the party:

But you’re right though.


(I think virtual functions work on references as well, but that wouldn’t be suitable for use in an array.)

1 Like

Oh right, haha got a bit confused

1 Like