Search code examples
c++inheritancemulti-level

C++ multilevel inheritance - Calling Base Constructor Error


So I have a fairly complex programm that I dont whant to go into right now. I will include a toy example of the same process and then go over it in more detail.

In my Programm I encounter the Error constructor for 'Hunter' must explicitly initialize the base class 'WorldObject' which does not have a default constructor with multilevel inheritance: WorldObject -> Creature -> Hunter.

To recreate the same structure I made the following:

class Base
{
protected:
    int a;
public:
    Base(int a): a(a) { print("Base contructed"); }
    ~Base() { print("Base destroyed"); }
    virtual void printData() = 0;
};



class Derived1 : public Base
{
protected:
    int b;
public:
    Derived1(int a, int b): b(b), Base(a) { print("Derived1 contructed"); }
    ~Derived1() { print("Derived1 destroyed"); }
};


class Derived2 : public Derived1
{
protected:
    int c;
public:
    Derived2(int a, int b, int c) : c(c), Derived1(a, b) { print("Derived2 contructed"); }
    ~Derived2() { print("Derived2 destroyed"); }
    virtual void printData(){ //... }
}; 

Here, the constructor of Derived2 class created Derived1 via the initializer list and this in turn constructs Base "indirectly". This works like I expected.

However, in my complex Code, the Hunter class needs to explicitly call the WorldObject constructor. This looks like:

Hunter(sf::Texture &texture, float x, float y, sf::Font& font) : 
        WorldObject(texture,x, y, font),
        Creature(texture, x, y, font)
    { //... }

Here, The Creature constructor just passes every argument to the WorldObject constructor. WorldObject only has this constructor:

WorldObject(sf::Texture& texture, float x, float y, sf::Font& font) : m_sprite(texture)
{ //... }

and the used Creature constructor looks like this:

    Creature(sf::Texture &texture, float x, float y, sf::Font& font) : 
    WorldObject(texture, x, y, font), 
    NN(n_input_units, n_hidden_units, n_output_units)
{ //... }

Why do I need to initialize both WorldObject and Creature directly in my Programm, but in the toy example it works without the explicit Base constructor?

(( The pre-compiler is also complaining that there is no default constructor for WorldObject, and on compiling the above error appears))


Solution

  • I guess that in your complex code, Hunter directly inherits from WorldObject and not indirectly via Creature. If Creature inherits WorldObject, it will never be necessary for Hunter to pass any parameters to WorldObject.