Here's code from a header file where I declare two classes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class creature {
public:
int x, y;
int hp;
char symbol;
bool ismoveok (int, int);
virtualvoid domove (int, int);
void attack (creature*);
creature (int, int, int, char);
};
class player : public creature {
public:
void domove (int, int);
void move (int);
player (int, int, int, char);
};
And here's the constructors for them:
1 2 3 4 5 6 7 8 9 10 11 12 13
creature::creature (int cx, int cy, int chp, char csymbol) { // line 32
x = cx;
y = cy;
hp = chp;
symbol = csymbol;
}
player::player (int cx, int cy, int chp, char csymbol) { // line 39
x = cx;
y = cy;
hp = chp;
symbol = csymbol;
}
When I try to compile this, I get the following error:
1 2 3 4
creature.cpp: In constructor 'player::player(int, int, int, char)':
creature.cpp:39: error: no matching function for call to 'creature::creature()'
creature.cpp:32: note: candidates are: creature::creature(int, int, int, char)
creature.h:3: note: creature::creature(const creature&)
What exactly is the problem here? As far as I know, this error should only appear if the player class doesn't have its own constructor, but it does...
That error is telling you that your player constructor is not calling a creature constructor. With inheritance, you need to tell which base class constructor should be invoked by each derived class constructor. You do this by means of the initializer list:
1 2 3 4 5 6 7 8 9 10
player::player (int cx, int cy, int chp, char csymbol)
: creature(cx, cy, chp, csymbol) // <- calling creature(int, int, int, char) through an initializer list
{
//no need to do the rest since this is what gets done in the creature constructor
//x = cx;
//y = cy;
//hp = chp;
//symbol = csymbol;
}