Search code examples
c++classpolymorphismabstract-class

C++ No Appropriate Default Constructor I am lost


I am stuck on a problem involving Polymorphism. My code keeps telling me that there is no default constructor for my class in this case I named creature, even though I did instantiate a constructor that takes a string in the creature class. I have a feeling I am missing something very small here and was hoping someone could help me with this. The code is as follows below.

class Creature 
{
public:

Creature(string);
virtual void DoAction() = 0;
virtual void DrawOnScreen() = 0;


protected:
string CreatureName;
};


Creature::Creature(string pname)
{
this->CreatureName = pname;
}; 


class Monster : public Creature
{

Monster(string CreatureName);
void DoAction();

protected: 
string CreatureName;

};


Monster::Monster(string pname)
{
this->CreatureName = pname;
};

class Player : public Creature
{
Player(string CreatureName);
void DoAction();

protected:
string CreatureName;
};

Player::Player(string pname)
{
this->CreatureName = pname;
}

class WildPig : public Creature
{
WildPig(string CreatureName);
void DoAction();
protected:
string CreatureName;
};

WildPig::WildPig(string pname)
{
this->CreatureName = pname;
}

class Dragon : public Creature
{
Dragon(string CreatureName);
void DoAction();
protected:
string CreatureName;
};

Dragon::Dragon(string pname)
{
this->CreatureName = pname;
}

I only included the classes within this snippet to keep it short and focused on where I believe the problem lies. Any help would be greatly appreciated.


Solution

  • Monster::Monster(string pname)
    {
        this->CreatureName = pname;
    }
    

    is equivalent to

    Monster::Monster(string pname) : Creature()
    {
        this->CreatureName = pname;
    }
    

    And Creature doesn't have default constructor. You need:

    Monster::Monster(string pname) : Creature(pname) {}