2

Say I have an class called 'Tile'

class Tile 
{
    private:
        int x, y;
};

And a class called 'Door' that extends 'Tile'

class Door : Tile
{
    private:
        bool open;
};

Can I make an array of Tile objects, for instance to create a room, and then have a Door object in the same array since it is an extension of Tile? If not are there any alternatives that I could use to accomplish this?

user3499995
  • 43
  • 2
  • 7

1 Answers1

1

Can I put a child object into an array of parent objects?

No.

An object of type T is always of type T, never another type, even if that type is related. Arrays always contain objects of one single type.

If not are there any alternatives that I could use to accomplish this?

Reference T& and pointer T* can refer to an object whose type is derived from T. You cannot store references in an array though. So, you may use an array of pointers.

Perhaps the simplest and most flexible choice is an array of shared pointers:

std::shared_ptr<Tile> tiles[10];
eerorika
  • 232,697
  • 12
  • 197
  • 326