【发布时间】:2013-08-29 18:16:48
【问题描述】:
在关于calling virtual methods in ctors and dtors 的问题中,以下一段源代码引用自 C++ 标准:
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
// *****************
}
我的问题是:为什么在 B 的 ctor 中调用 a->f() 是未定义的行为?我们可以放心地假设,a 在传递给 B 的 ctor 之前已经分配好了,那为什么不能正常工作呢?
V * v = new V();
A * a = new A();
B * b = new B(v, a);
【问题讨论】:
标签: c++ inheritance polymorphism virtual