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


当前回答

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

其他回答

虚函数用于根据指针所指向的对象类型调用函数,而不是指针本身的类型。但是构造函数不会被“调用”。它只在声明对象时调用一次。因此,在c++中构造函数不能被设为虚函数。

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,那么它应该在它的派生类中以相同的名字重新定义,但两个类的名字不能相同。所以不可能有一个虚拟构造函数。

听可靠消息。:)

选自Bjarne Stroustrup的c++风格和技术常见问题解答为什么没有虚拟构造函数?

虚拟调用是一种在给定局部条件下完成工作的机制 信息。特别地,“virtual”允许我们调用一个函数 只知道任何接口,而不知道对象的确切类型。来 创建对象时需要完整的信息。特别是,你 需要知道你想要创建的确切类型。因此, “对构造函数的调用”不能是虚的。

FAQ条目继续给出了一种不使用虚拟构造函数实现此目的的方法的代码。

你也不应该在构造函数中调用虚函数。参见:http://www.artima.com/cppsource/nevercall.html

另外,我不确定是否真的需要虚拟构造函数。你可以在没有它的情况下实现多态构造:你可以编写一个函数,根据所需的参数构造你的对象。

抛开语义上的原因不谈,在对象被构造之后才有虚表,因此虚表的指定是无用的。