virtual constructor in c++ [duplicate]
Possible Duplicate:
Why do we not have a virtual constructor?
why we dont have virtual constructor in c++?
C++ classes are not first class objects - there's no way, like in java, to make a variable that refers to a class and invoke construction based on this variable. So, a virtual constructor does not make sense, since you always know the type of the object you create.
How would it work? What would you want to achieve with it?
You need to have an object in order to have a virtual-table / function-table, but when you are in the constructor you don't have an object yet, as it is under construction.
What you probably do want is an abstract factory. That will create a different class in an "abstract" way, eg:
class Base { public: virtual ~Base() {} };
class Derived1 : public Base
{
};
class Derived2 : public Base
{
};
class BaseFactory
{
public:
virtual ~BaseFactory() {}
virtual Base * create() const = 0;
};
class Derived1Factory : public BaseFactory
{
public:
// could also return Derived1*
Base * create() const { return new Derived1; }
};
class Derived2Factory : public BaseFactory
{
public:
// could also return Derived2*
Base * create() const { return new Derived2; }
};
// abstractly construct a Base
Base * createABase( const BaseFactory & fact )
{
return fact.create();
}
精彩评论