6

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);
Community
  • 1
  • 1
Spook
  • 25,318
  • 18
  • 90
  • 167

1 Answers1

2

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621