c++ - 构造函数不能是虚拟的,为什么?不是骗子

标签 c++ constructor virtual

<分区>

Possible Duplicate:
Why do we not have a virtual constructor?

我知道之前有人问过这个问题,但我不明白其他答案中使用的复杂技术词汇。

我在社区上读到构造函数不能是虚拟的原因是

The ‘virtual’ mechanism works on a logically complete (completely constructed) object. We know that we use constructors to logically initialize our objects. In other words, the object is not completely constructed until the constructor has finished executing. Thus, we can’t have virtual constructors.

There is a misconception that by then virtual table is incomplete so we can’t have virtual constructors. Just before the constructor starts executing the virtual table is properly constructed and the ‘this’ pointer passed to the constructors. Moreover, virtual table mechanism is implementation depended, and finds no place in the C++ standard. And hence, to argue over this issue using the virtual table concept is illogical.

Now, as the constructor finishes executing any other function can be virtual. Destructor is no exception to this rule as it is a function. Virtual destructors are required in case we use a base class pointer to refer to a derived class object, use it, and then delete it. If we have virtual destructor, using ‘delete’, a chain of destructors is called starting from the derived to the base. But, had there been no ‘virtual’ in destructor only the base class destructor is called (and not the derived). This (may) generate inconsistencies in the program.

以上理由是否正确?答案不谈对象的静态类型和动态类型。

最佳答案

虚拟构造函数没有意义,也不是必需的。唯一一次调用构造函数是在创建对象时。您需要知道对象的类型才能创建它,因此静态类型和动态类型是相同的,要调用的正确构造函数是该类型的构造函数。

这就是为什么它们不是必需的。为什么它们没有意义,是因为在创建对象时,基类构造函数被称为以及派生类构造函数。如果在派生类中重写了基类构造函数,是否意味着根本没有调用基类构造函数?

其他语言有虚构造函数,可能是因为那些语言的构造函数是方法,它们只有非静态方法的虚调用。但是那些其他语言(我想到了 Java 和 Python)必须引入特殊规则,构造函数必须/应该将其基类显式构造为来自构造函数的调用。 C++ 只是这样做(可能在初始化列表中,如果基类构造函数需要参数),使用非虚拟构造函数,并且没有选项可以使用未初始化的基类子对象进入构造函数的主体。

关于c++ - 构造函数不能是虚拟的,为什么?不是骗子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3820774/

相关文章:

c++ - 与 c/c++ 中的结构指针混淆

c++ - 使用qt c++检查Xml中是否存在根元素

c++ - 如何快速将 IplImage(OpenCV) 转换为 ALLEGRO_BITMAP (A5)?

.net - 试图理解 F# 类定义语法

java - 扩展抽象构造函数?

C++ 指向派生类对象的基类指针不调用派生等于运算符函数

c++ - JavaScript 无法访问 XPCOM 对象方法

java - ArrayList构造函数错误

c++ - 如何在运行时决定将哪个派生类用作 C++ 中的私有(private)类成员?

function - 具有虚函数的类中的非虚函数