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


当前回答

与面向对象的语言(如Smalltalk或Python)不同,这些语言的构造函数是表示类的对象的虚拟方法(这意味着您不需要GoF抽象工厂模式,因为您可以传递表示类的对象,而不是自己创建),c++是一种基于类的语言,并且没有表示语言的任何构造的对象。该类在运行时不作为对象存在,因此不能对其调用虚方法。

这符合“不用就不用付钱”的理念,尽管我所见过的每个大型c++项目最终都实现了某种形式的抽象工厂或反射。

其他回答

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

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;
}

听可靠消息。:)

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

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

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

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.

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.

与面向对象的语言(如Smalltalk或Python)不同,这些语言的构造函数是表示类的对象的虚拟方法(这意味着您不需要GoF抽象工厂模式,因为您可以传递表示类的对象,而不是自己创建),c++是一种基于类的语言,并且没有表示语言的任何构造的对象。该类在运行时不作为对象存在,因此不能对其调用虚方法。

这符合“不用就不用付钱”的理念,尽管我所见过的每个大型c++项目最终都实现了某种形式的抽象工厂或反射。