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++?

3
  • 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... Commented Jun 30, 2014 at 19:12
  • @user3316633: Also, please note that ~Tile() should be declared virtual. See this question for details on why. Commented Jun 30, 2014 at 19:18
  • @Edward only if you plan to use polymorphism Commented Jun 30, 2014 at 19:19

1 Answer 1

9

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

class TileGrass : public Tile { public: TileGrass() : Tile(some_color) { // .... } ~TileGrass(); }; 
Sign up to request clarification or add additional context in comments.

3 Comments

I believe this is actually called inheriting constructors in the ISO standard as well.
@TheFloatingBrain Inheriting constructors refers to a different thing. For example, using Tile::Tile would let you construct TileGrass t(some_color); without having to declare and define TileGrass(Color&).
@TheFloatingBrain See Inheriting constructors

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.