Hence we have the classical diamond problem and int's solution:
class A
{
public:
A()
{
std::cout << "A c'tor" << std::endl;
}
void f()
{
std::cout << "A::f()" << std::endl;
}
};
class B :virtual public A{};
class C :virtual public A{};
class D : public B, public C{};
How does the compiler handles this, so it creates only one instance of A? Please answer as specific as you can.
Standard doesn't specify how should compiler handle that, but usually (AFAIK gcc
and MSVC
), it's implemented the way I described below.
When class inherits normally, it will contain all of base class members
When class inherits virtually, it will (instead of whole class) contain pointer to where that base class resides, virtual base class shall reside in most derived object:
struct A
{
int i;
};
struct B: virtual A{};
struct C: B{};
int someFunction()
{
/* b internally contains pointer that points to it's (virtual)base class ,
in this case B itself is most derived object so it points to base class
which is stored somewhere inside B */
B b;
/* now subobject B (which is stored inside C) contains pointer that
,again points to it's (virtual) base class
,but that class now resides in most derived object which is C */
C c;
}
Extra points:
Can you figure out where is the error?
struct A
{
std::string message;
A(std::string parameter): message(parameter) {}
};
struct B: virtual A
{
B(std::string parameter): A(parameter) {}
};
struct C: B
{
C(){}
};