C++中构造函数能调用虚函数吗?

来源:互联网 发布:网络写手现状究竟如何 编辑:程序博客网 时间:2024/05/09 13:59


  在调用Base的构造函数时已经出现了虚函数表指针,这个指针指向Base的虚函数表,所以在Base的构造函数中调用的虚函数其实都是Base的虚函数;

而在构造A时,虚函数表指针被指向了A的虚函数表,所以此时调用的虚函数其实是A的虚函数表中的项。

也就是说多态这个功能被屏蔽了。


C++标准2.7对此有明文规定

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 (including the mem-initializer or
brace-or-equal-initializer for a non-static data member) or from a destructor, and the object to which the
call applies is the object under construction or destruction, the function called is the one defined in the
constructor or destructor’s own class or in one of its bases, but not a function overriding it in a class derived
from the constructor or destructor’s class, or overriding it in one of the other base classes of the most derived
object (1.8). If the virtual function call uses an explicit class member access (5.2.5) and the object-expression
refers to the object under construction or destruction but its type is neither the constructor or destructor’s
own class or one of its bases, the result of the call is undefined.

0 0
原创粉丝点击