i have the following scenario:
class A
{
public:
A(std::string id);
};
class B : public virtual A
{
public:
B();
};
class C : public virtual A
{
public:
C();
};
class D : public B, public C
{
public:
D(std::string id);
};
D::D(std::string id) : A(id), B(), C()
{
}
class X : public D
{
public:
X(std::string id);
}
X::X(std::string id) : D(id)
{
}
Now, if i create an instance of D everything works fine. However if i create an instance of X i get a compiler error which tells me that something tries to call the default constructor of A – which does not exist. If i create it, it compiles but only the default constructor is called and accordingly, id is not correctly set/initialized.
This can be fixed by implementing the constructor of X like so:
X::X(std::string id) : A(id), D(id)
{
}
But my understanding is, that this should be unnecessary. So where’s my error ?
You need to make all your constructors
publicand define a default constructor forAbecause the string constructor will mark the default constructor as=delete. Furthermore, the most derived class will initialize any virtual base class, quoting from the draft Standard:12.6.2 Initializing bases and members [class.base.init]
In this case that means that
Xmust indeed initalizeA.