Execution order in case of multiple inheritance

class A: public B, public C { };

In this case, the execution order:

B(); // base(first)  
C(); // base(second)  
A(); // derived

class A: public B, virtual public C { }; 

But in this case, when I write virtual with class c when inheriting, the order

// execution becomes:  
C(); // virtual base  
B(); // ordinary base  
A(); // derived

I read somewhere that the order in which the constructor is called depends on the order of the declaration when several classes are inherited, but how the execution order changes when writing the virtual with the class. I can’t get why I get such a result.

+4
source share
2 answers

Constructors of a virtual base class are always executed first in accordance with the C ++ standard. From working draft N3242 , p. 272, line 10, we learn that:

  • , .
  • , .

, , , , ++. , , , , . , , .

.

+5

, , . , (, ) . , .

, ++ , . @Dan Roche, .

:

class B: public A {...}
class C: public B, virtual A {...}

C B A, B A.

, :

#include <iostream>
using namespace std;

struct A {
  A() {cout<<"A()"<<endl;}
};

struct B {
  B() {cout<<"B()"<<endl;}
};

struct C: virtual A, virtual B {
  C() {cout<<"C()"<<endl;}
};

struct D: virtual B, virtual A, C {
  D() {cout<<"D()"<<endl;}
};  

int  main() {
  cout<<"construct C"<<endl;
  new C;
  cout<<"construct D"<<endl;
  new D;
}

:

construct C
A()
B()
C()
construct D
B()
A()
C()
D()

, C D, A B . , , , - .

+1

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


All Articles