c++ Virtual/Non-virtual Diamond inheritance -
given following code in c++:
struct { a() { f(0); } a(int i) { f(i); } virtual void f(int i) { cout << i; } }; struct b1 : virtual { b1(int i) : a(i) { f(i); } virtual void f(int i) { cout << i+10; } }; struct b2 : virtual { b2(int i) : a(i) { f(i); } virtual void f(int i) { cout << i+20; } }; struct c : b1, virtual b2 { int i; c() : b1(6),b2(3),a(1){} virtual void f(int i) { cout << i+30; } };
can explain why c* c = new c()
; print 1 23 , 16 in order? how decide order print in? know nonvirtual b1
called last why a()
called first? , explanation ahead of time.
because virtually inheriting b2
, compiler construct first identify variables virtually inherited in c
before constructs non-virtual inheritance (b1
). of course, a
gets constructed first because b2
needs before can constructed.
Comments
Post a Comment