Virtual multiple inheritance

I came across this code example:

#include <iostream> using namespace std; class A { int x; public: A() { x = 1; cout << "A"; } }; class B : virtual public A { int y; public: B() { y = 2; cout << "B"; } }; class C : virtual public B, virtual public A { int z; public: C() { z = 3; cout <<"C"; } }; class D : public A, public B, public C { int t; public: D() { t = 4; cout << "D"; } }; int main() { D d; return 0; } 

This code prints ABABCD , and I have no idea why. I thought it would print A for D : public A , then AB for D : public B , then ABC for D : public C , and then D , but it seems like A is being printed twice. How it works?

+6
source share
1 answer

The order of constructing bases (ignoring virtual bases) is from left to right, since they are typed in relation to inheritance. As soon as you add virtual databases, they are first initialized (before any non-virtual database) from the first glance from left to right.

Now this should explain the result.

D: A, B, C

A has no virtual bases, B has a virtual base A, so the first is initialized: "A". Then C has a virtual base B, so the next next one is initialized. At this point, the virtual subobject A is already initialized, so only constructor B evaluates to "AB". At this stage, all virtual bases were built and non-virtual bases were built, first A, then B, then C, then the full type D, giving "ABABCD". All virtual sub-objects are built, so they are not created again.

Some things to keep in mind. A virtual database is shared only with other subobjects that want to share it (i.e., have it as a virtual database). There is no limit as to how many times the virtual database can be shared in a full object (i.e., virtual database A is shared several times, including from different subobjects B)

+8
source

Source: https://habr.com/ru/post/946891/


All Articles