为什么c++没有虚构造函数?
当前回答
面试答案是:virtual ptr和table是和对象相关的,而不是和类相关的。因此构造函数构建虚表 因此,我们不能有虚构造函数,因为在创建obj之前没有虚表。
其他回答
听可靠消息。:)
选自Bjarne Stroustrup的c++风格和技术常见问题解答为什么没有虚拟构造函数?
虚拟调用是一种在给定局部条件下完成工作的机制 信息。特别地,“virtual”允许我们调用一个函数 只知道任何接口,而不知道对象的确切类型。来 创建对象时需要完整的信息。特别是,你 需要知道你想要创建的确切类型。因此, “对构造函数的调用”不能是虚的。
FAQ条目继续给出了一种不使用虚拟构造函数实现此目的的方法的代码。
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.
c++的虚拟构造函数是不可能的。例如,不能将构造函数标记为虚函数。试试这段代码
#include<iostream.h>
using namespace std;
class aClass
{
public:
virtual aClass()
{
}
};
int main()
{
aClass a;
}
它会导致错误。这段代码试图将构造函数声明为虚函数。 现在让我们试着理解为什么要使用virtual关键字。Virtual关键字用于提供运行时多态性。例如,试试这段代码。
#include<iostream.h>
using namespace std;
class aClass
{
public:
aClass()
{
cout<<"aClass contructor\n";
}
~aClass()
{
cout<<"aClass destructor\n";
}
};
class anotherClass:public aClass
{
public:
anotherClass()
{
cout<<"anotherClass Constructor\n";
}
~anotherClass()
{
cout<<"anotherClass destructor\n";
}
};
int main()
{
aClass* a;
a=new anotherClass;
delete a;
getchar();
}
In main a=new anotherClass; allocates a memory for anotherClass in a pointer a declared as type of aClass.This causes both the constructor (In aClass and anotherClass) to call automatically.So we do not need to mark constructor as virtual.Because when an object is created it must follow the chain of creation (i.e first the base and then the derived classes). But when we try to delete a delete a; it causes to call only the base destructor.So we have to handle the destructor using virtual keyword. So virtual constructor is not possible but virtual destructor is.Thanks
抛开语义上的原因不谈,在对象被构造之后才有虚表,因此虚表的指定是无用的。
尽管由于对象类型是对象创建的先决条件,所以虚拟构造函数的概念不太适合,但它并没有完全被推翻。
GOF的“工厂方法”设计模式利用了虚拟构造函数的“概念”,这在某些设计情况下很方便。