Understanding virtual base classes and constructor calls

前端 未结 2 1716
温柔的废话
温柔的废话 2020-12-06 11:01

I\'m a bit confused about how virtual base classes work. In particular, I was wondering how the constructor of the base class gets called. I wrote an example to understand

相关标签:
2条回答
  • 2020-12-06 11:27

    There is always just one constructor call, and always of the actual, concrete class that you instantiate. It is your responsibility to endow each derived class with a constructor which calls the base classes' constructors if and as necessary, as you did in B's constructor.

    Update: Sorry for missing your main point! Thanks to ildjarn.

    However, your B inherits virtually from A. According to the standard (10.1.4 in the FIDS), "for each distinct baseclass that is specified virtual, the most derived object shall contain a single base class subobject of that type". In your case this means that when constructing the base, your class F immediately calls A's default constructor, not B's.

    0 讨论(0)
  • 2020-12-06 11:37

    Virtual base classes are always constructed by the most derived class.

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