为什么c++没有虚构造函数?


当前回答

有一个非常基本的原因:构造函数实际上是静态函数,而在c++中没有静态函数可以是虚函数。

如果你有丰富的c++经验,你就会知道静态函数和成员函数之间的区别。静态函数与CLASS相关联,而不是与对象(实例)相关联,因此它们看不到“this”指针。只有成员函数可以是虚函数,因为虚表——使“虚”工作的函数指针的隐藏表——实际上是每个对象的数据成员。

构造函数的任务是什么?它在名称中——“T”构造函数在分配T对象时初始化它们。这将自动排除它成为成员函数!对象必须先存在,然后才有this指针,从而有虚表。这意味着即使语言将构造函数视为普通函数(它并没有,由于相关原因,我不会深入讨论),它们也必须是静态成员函数。

了解这一点的一个好方法是查看“Factory”模式,特别是工厂函数。它们做你想做的事情,你会注意到,如果类T有一个工厂方法,它是ALWAYS STATIC。这是必须的。

其他回答

我们不能简单地说…我们不能继承构造函数。因此没有必要将它们声明为虚拟的,因为虚拟提供了多态性。

If you think logically about how constructors work and what the meaning/usage of a virtual function is in C++ then you will realise that a virtual constructor would be meaningless in C++. Declaring something virtual in C++ means that it can be overridden by a sub-class of the current class, however the constructor is called when the objected is created, at that time you cannot be creating a sub-class of the class, you must be creating the class so there would never be any need to declare a constructor virtual.

另一个原因是,构造函数的名字与其类名相同如果我们将构造函数声明为virtual,那么它应该在它的派生类中以相同的名字重新定义,但两个类的名字不能相同。所以不可能有一个虚拟构造函数。

在创建对象时创建Vpointer。创建对象前Vpointer不存在。因此,没有必要将构造函数设为虚函数。

A virtual-table(vtable) is made for each Class having one or more 'virtual-functions'. Whenever an Object is created of such class, it contains a 'virtual-pointer' which points to the base of corresponding vtable. Whenever there is a virtual function call, the vtable is used to resolve to the function address. Constructor can not be virtual, because when constructor of a class is executed there is no vtable in the memory, means no virtual pointer defined yet. Hence the constructor should always be non-virtual.

你可以在@stefan的回答中找到一个例子和为什么不允许这样做的技术原因。在我看来,这个问题的合理答案是:

virtual关键字的主要用途是在我们不知道基类指针将指向什么类型的对象时启用多态行为。

但这是一种更原始的方式,对于使用虚拟功能,你需要一个指针。指针需要什么?一个指向的对象!(考虑程序正确执行的情况)

因此,我们基本上需要一个已经存在于内存某处的对象(我们不关心内存是如何分配的,它可能是在编译时或运行时),以便我们的指针能够正确地指向该对象。

现在,想象一下当要指向的类的对象被分配一些内存时的情况——>它的构造函数将在该实例本身被自动调用!

所以我们可以看到,我们实际上不需要担心构造函数是虚的,因为在任何情况下,你希望使用多态行为,我们的构造函数已经执行,使我们的对象准备使用!