首页 > 解决方案 > Do I need to initialize base class in virtual inheritance classes' constructors for diamond inheritanceproblem?

问题描述

I have the diamond problem resolved with virtual inheritance. The situation here is not a diamond but I want to understand the virtual inheritance:

class Base
{
public:
    explicit Base(int arg)
        : arg { arg }
    {}
    const int arg;
};

class Virtual : public virtual Base
{
public:
    explicit Virtual(int _arg)
        //: Base(_arg)
    {}
};

class Target : public virtual Virtual
{
public:
    explicit Target(int _arg)
        : Base(_arg),
          Virtual(_arg)
    {}
};

So, the idea is that Virtual or Virtual2, inherited together by Target, will have single Base instance. Here I thought that calling Base constructor in Target constructor will create the instance needed and I could omit Base constructor in Virtual, but then I'm getting an error:

error: constructor for 'Virtual' must explicitly initialize the base class 'Base' which does not have a default constructor

So, is the constructor there really necessary if it's suppose not to be called?

In real situation I am making some changes to arguments with lambda within the constructors so I don't know if it needs to be repeated.

标签: c++c++17

解决方案


As you have written, both Virtual and Target needs to provide a constructor for Base.

If you make Virtual abstract, then it does not need to initialize Base any longer.

class Base
{
public:
    explicit Base(int arg)
        :  arg(arg)
    {}
private:
    const int arg;
};

class Virtual : public virtual Base
{
public:
    explicit Virtual(int arg)
    {}
private:
    virtual void foo() = 0;
};

class Target : public virtual Virtual
{
public:
    explicit Target(int arg)
        : Base(arg), Virtual(arg)
    {}
private:
    virtual void foo() override {}
};

推荐阅读