Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling virtual methods of other classes in ctors

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);
like image 471
Spook Avatar asked Aug 27 '13 05:08

Spook


1 Answers

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.

like image 139
Some programmer dude Avatar answered Nov 01 '22 20:11

Some programmer dude