开发者

virtual constructor in c++ [duplicate]

This question already has answers here: 开发者_StackOverflow社区 Closed 11 years ago.

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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜