No matching function in multiple inheritance

978 Views Asked by At

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.

2

There are 2 best solutions below

0
R Sahu On BEST ANSWER
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.

0
Danh On

sub_three constructor initializes base, and call the default constructor of sub_one and sub_two which doesn't exist, you may need

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), sub_one(a,b), sub_two(a,b,c), flag(false)
    {
        // do something    
    }
};