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


当前回答

虚函数基本上提供多态行为。也就是说,当您使用的对象的动态类型与引用它的静态(编译时)类型不同时,它提供的行为适合于对象的实际类型,而不是对象的静态类型。

现在尝试将这种行为应用于构造函数。当你构造一个对象时,静态类型总是与实际的对象类型相同,因为:

要构造一个对象,构造函数需要它要创建的对象的确切类型[…]此外[…]]则不能有指向构造函数的指针

Bjarne Stroustup (P424 c++编程语言SE)

其他回答

我们有,只是它不是一个构造函数:-)

struct A {
  virtual ~A() {}
  virtual A * Clone() { return new A; }
};

struct B : public A {
  virtual A * Clone() { return new B; }
};

int main() {

   A * a1 = new B;
   A * a2 = a1->Clone();    // virtual construction
   delete a2;
   delete a1;
}

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

The virtual mechanism only works when you have a based class pointer to a derived class object. Construction has it's own rules for the calling of base class constructors, basically base class to derived. How could a virtual constructor be useful or called? I don't know what other languages do, but I can't see how a virtual constructor could be useful or even implemented. Construction needs to have taken place for the virtual mechanism to make any sense and construction also needs to have taken place for the vtable structures to have been created which provides the mechanics of the polymorphic behaviour.

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条目继续给出了一种不使用虚拟构造函数实现此目的的方法的代码。