且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在构造函数中调用纯虚函数会产生错误

更新时间:2023-11-12 21:34:40

在构造函数中调用虚函数是被认为是一件不好的事情。

Calling virtual functions in a constructor is recognised as a bad thing to do.


在派生类对象的基类构造期间,对象的类型
是基类的类型。不仅虚拟函数
解析到基类,而且语言的部分使用运行时
类型信息(例如dynamic_cast(参见项目27)和typeid)将
对象视为一个基类类型。

During base class construction of a derived class object, the type of the object is that of the base class. Not only do virtual functions resolve to the base class, but the parts of the language using runtime type information (e.g., dynamic_cast (see Item 27) and typeid) treat the object as a base class type.

所以你的实例化 b 调用 a 构造函数。调用 foo(),但它是 foo() a 被调用。而且(当然)是未定义的。

So your instantiation of b invokes the a constructor. That calls foo(), but it's the foo() on a that gets called. And that (of course) is undefined.