c++ - 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.
解决方案
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 {}
};
推荐阅读
- c# - 从列表中添加值
到数据库列 - java - 试图为休眠条件搜索制定方法
- javascript - 如何将类属性传递给嵌套在 NodeJS 中的 class>method>each 中的 .each 块?
- json - 在 SQL 中使用 JSON 数组
- amazon-dynamodb - this.user().context 未定义 - Jovo 框架 - Alexa
- java - @Transactional 适用于服务中的公共方法,但不适用于受保护的方法
- apache - 如何通过 Apache 安全更新禁用切换回 mpm_prefork?
- java - 使用 Java 编辑 JSON 文件,其中文件位于远程位置:SSH 可用
- r - 如何使 actionButton 仅在 R 闪亮中给出所有输入时才起作用?
- python - Python烧瓶线程不关闭