0

I have a class, Tile, that has a constructor with parameters of a Color object:

class Tile
{
public:
    static const int size = 32;

    Tile();
    Tile(Color &color);

    void render(int x, int y);

    Color getColor();

    ~Tile();
private:
    Color _color;
};

Then I have a subclass, TileGrass, which inherits Tile:

class TileGrass : public Tile
{
public:
    TileGrass();
    ~TileGrass();
};

Now the issue is that the TileGrass needs to inherit the Tile constructor with the Color parameters. But, the TileGrass object already knows what color it needs to give to the superclass, so I don't want to have to pass in a Color object when creating a new TileGrass object. In Java I can do something like this:

public class TileGrass extends Tile {

public TileGrass() {
    super(color object);
}
}

How can I do something like this in C++?

David G
  • 94,763
  • 41
  • 167
  • 253
user3316633
  • 137
  • 5
  • 13
  • In C++(11) inheriting constructors means being able to call a constructor of the base class to build a derived object. Here you just want to call a specific base constructor inside the derived constructor, pretty standard thing... – DarioP Jun 30 '14 at 19:12
  • @user3316633: Also, please note that `~Tile()` should be declared virtual. See [this question](http://stackoverflow.com/questions/270917/why-should-i-declare-a-virtual-destructor-for-an-abstract-class-in-c) for details on why. – Edward Jun 30 '14 at 19:18
  • @Edward only if you plan to use polymorphism – DarioP Jun 30 '14 at 19:19

1 Answers1

9

Just call the relevant base class constructor in the initialization list:

class TileGrass : public Tile
{
 public:
  TileGrass() : Tile(some_color) 
  {
    // ....
  }

  ~TileGrass();
};
juanchopanza
  • 223,364
  • 34
  • 402
  • 480