Search code examples
c++c++11inheritancemultiple-inheritancedelegating-constructor

No matching function in multiple inheritance


I'm new to inheritance in C++ and decided to try some experiments to learn about this subject.

The code below shows the hierarchy of classes I'm creating:

classes.h

class base
{
protected:
    int _a;
    int _b;
    int _c;;
    base(int b, int c);
};

class sub_one : public virtual base
{
public:
    sub_one(int a, int b) : base(a, b)
    {
        // do some other things here
    }

    // other members
};


class sub_two : public virtual base
{
protected:
    int _d;
public:
    sub_two(int a, int b, int c = 0) : base(a, b) 
    {
        // do something
    }

    // other members
};


class sub_three : public sub_one, public sub_two
{
private:
    bool flag;
public:
    sub_three(int a, int b, int c = 0) : base(a, b) 
    {
        // do something    
    }
};

classes.c

base::base(int a, int b)
{
    // ...
}

The compiler shows me the messages:

no matching function for call to sub_one::sub_one()

no matching function for call to sub_one::sub_one()

no matching function for call to sub_two::sub_two()

no matching function for call to sub_two::sub_two()

I just can't find out what is wrong.


Solution

  • sub_three(int a, int b, int c = 0) : base(a, b) 
    {
        // do something    
    }
    

    is equivalent to:

    sub_three(int a, int b, int c = 0) : base(a, b), sub_one(), sub_two() 
    {
        // do something    
    }
    

    Since there are no such constructors in sub_one and sub_two, the compiler reports the errors. You can add default constructors to sub_one and sub_two to remove the errors.