I programmed a simple board game to learn C ++ concepts in practice. I implemented a board: it consists of tiles, each of which is a child class, inheriting from the parent class. A circuit board is a class that has a fragment vector.
There are several types of tiles. Some of them can be bought by players. There are several different types of tiles to buy, as well as with different properties, so I found it nice to make the base class TileOnSale for tiles that you can buy, and create child classes of real types, two of which I presented in the code below.
Now my problem is how can I access the functions of children that are not defined in the parent class (TileOnSale)? The board gets initialized with all kinds of different fragments, so I can extract the Tile from there using the getTile (int location) function. However, this is interpreted as simply Tile, not TileOnSale or StreetTile. I do not know how to understand how StreetTile buildHouses function in this way.
So, is there a reliable or even better way to do this? Can I create a template or something to hold Tile objects that can be StreetTiles or StationTiles or something else that is Tile? Or am I just redesigning the class structure?
Here is the bone code. I tried to provide only what is needed to understand the issue. In addition, Tile and Board were originally in their header files. I decided that it was not necessary to show the Player class, which has a vector of objects belonging to TileOnSale, but which retains the same access problem as Board.
#include "Tile.h"
typedef vector<Tile> Tiles;
class Board
{
public:
Board();
~Board();
Tile getTile(int location);
private:
Tiles tiles;
};
class Tile
{
public:
Tile();
~Tile();
protected:
tileType tile_type;
string description;
};
class TileOnSale : public Tile
{
public:
TileOnSale();
~TileOnSale();
virtual int getRent() const { return 0; };
};
class StreetTile : public TileOnSale
{
public:
StreetTile();
~StreetTile();
int getRent() override;
void buildHouses(int number);
private:
int houses;
};
class StationTile : public TileOnSale
{
public:
StationTile();
~StationTile();
int getRent() override;
};
EDIT: Added a potentially clarifying comment on the code.
source
share