In the question about calling virtual methods in ctors and dtors the following piece of source code is cited from the C++ standard:
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's ctor is an undefined behavior? We can safely assume, that a
is already allocated before passing to B's ctor, so why wouldn't that work correctly?
V * v = new V();
A * a = new A();
B * b = new B(v, a);
The a->f()
call is undefined when you create an object of type D
.
In your own example, the a->f()
is okay, since you have created a separate A
instance before creating the B
instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With