May I call a virtual function to initialize a base-class sub-object?

前端 未结 1 1854
忘掉有多难
忘掉有多难 2020-12-12 02:10

I know that virtual functions should not be called either directly or indirectly in a constructor, but this code runs fine.
Is what I have here safe?

#in         


        
相关标签:
1条回答
  • 2020-12-12 02:20

    Invoking virtual members in the constructor and/or destructor is generally ok.

    It's a different game in the ctor initializer though, before all bases are initialized:

    12.6.2 Initializing bases and members [class.base.init]

    [...]
    14 Member functions (including virtual member functions, 10.3) can be called for an object under construction. Similarly, an object under construction can be the operand of the typeid operator (5.2.8) or of a dynamic_cast (5.2.7). However, if these operations are performed in a ctor-initializer (or in a function called directly or indirectly from a ctor-initializer) before all the mem-initializers for base classes have completed, the result of the operation is undefined.

    0 讨论(0)
提交回复
热议问题