Call a virtual function from a member constructor

I am wondering what the following looks like:

#include <iostream> #include <string> struct A; struct B { std::string b; B(A& a); }; struct A { B member; virtual std::string f() { return "Hello, World!"; } A() : member(*this) {} }; B::B(A& a) : b(af()) {} int main() { std::cout << A().member.b; } 

Does the expected result need to be printed? Or is this behavior undefined?

+5
source share
1 answer

It is legal. ยง12.7 [class.cdtor] / p4:

Member functions, including virtual functions (10.3), can be called during construction or destruction (12.6.2). When a virtual function is called directly or indirectly from a constructor or from a destructor, including during construction or classes non-static data elements and the object to which the object is called (call it x ) under construction or destruction, the called function is the final override in the constructors or class of destructors , not one that overrides it in a more derived class. If a call to a virtual function uses access to the explicit members of the class (5.2.5), and the expression of the object refers to the full object x or one of these subobjects of the base class, but not x or one of its subobjects of the base class, the behavior is undefined.

The UB case does not apply here.

+6
source

Source: https://habr.com/ru/post/1202068/


All Articles