सवाल में अन्य वर्गों की आभासी तरीकों कॉलिंग calling virtual methods in ctors and dtors के बारे में स्रोत कोड का टुकड़ा निम्नलिखित सी ++ मानक से उद्धृत किया जाता है:ctors
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
// *****************
}
मेरा प्रश्न है: क्यों बी के ctor में a->f()
बुला एक अपरिभाषित व्यवहार है ? हम सुरक्षित रूप से मान सकते हैं कि a
पहले ही बी के सीटीआर से गुजरने से पहले आवंटित किया गया है, तो यह सही तरीके से क्यों काम नहीं करेगा? जब आप प्रकार D
की एक वस्तु बनाने
V * v = new V();
A * a = new A();
B * b = new B(v, a);