Calling virtual methods of other classes in ctors

In the question about invoking virtual methods in ctors and dtors , the following code fragment from the C ++ standard is given:

struct V { virtual void f(); virtual void g(); }; struct A : virtual V { virtual void f(); }; struct B : virtual V { virtual void g(); B(V*, A*); }; struct D : A, B { virtual void f(); virtual void g(); D() : B((A*)this, this) { } }; B::B(V* v, A* a) { f(); // calls V::f, not A::f g(); // calls B::g, not D::g v->g(); // v is base of B, the call is well-defined, calls B::g // *** This line *** a->f(); // undefined behavior, a's type not a base of B // ***************** } 

My question is: why calling a->f() in B ctor is this undefined behavior? We can safely assume that a already highlighted before switching to B ctor, so why doesn't it work correctly?

 V * v = new V(); A * a = new A(); B * b = new B(v, a); 
+6
source share
1 answer

Call a->f() undefined when creating an object of type D

In your own example, a->f() is fine, since you created a separate instance of A before creating the instance of B

+2
source

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


All Articles