c++ - Understanding base class initialization -
consider program:
#include<iostream> #include<vector> struct { int a; a(int) { } virtual int foo(){ std::cout << "base" << std::endl; return 5; } }; struct b : { int b; b(): b(9), a(foo()) { } virtual int foo(){ std::cout << "derived" << std::endl; return 6; } }; b b; //prints derived int main(){ }
what scott meyers in effective c++
said :
during base class construction of derived class object, type of object of base class.
so, expected base
printed instead, because under base class class construction while invoking foo
function. did miss? maybe it's ub? if so, please point me out relevant section.
scott means while in base class constructor usual rules virtual function don't work. if in base class constructor virtual functions(of base class) called inside ctor called on object under construction in ctor.
so code prints correct result: foo()
called in b
's ctor not in parent constructor. if called foo
inside a
ctor have base
printed.
still behavior deemed undefined according standard:
[12.6.2/13] member functions (including virtual member functions, 10.3) can called object under construction. similarly, object under construction can operand of typeid operator (5.2.8) or of dynamic_-cast (5.2.7). however, if these operations performed in ctor-initializer (or in function called directly or indirectly ctor-initializer) before mem-initializers base classes have completed, resultof operation undefined.
but should understand "undefined" here means might use internal state in called function. since don't behavior consistent standard still deems undefined. "undefined" part have nothing printed rather might accessed in member function.
Comments
Post a Comment