0

Possible Duplicate:
Why do we not have a virtual constructor?

why we dont have virtual constructor in c++?

Community
  • 1
  • 1
Vijay
  • 65,327
  • 90
  • 227
  • 319
  • 2
    What would a virtual constructor do? – Jon Mar 15 '11 at 13:37
  • 1
    Jon, see http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.8. I think the idea is to have a function that can construct different values in an inheritance hierarchy. – Jeff Foster Mar 15 '11 at 13:38
  • 1
    Your exact question is answered by Stroustroup: http://www2.research.att.com/~bs/bs_faq2.html#virtual-ctor – wkl Mar 15 '11 at 13:38

2 Answers2

0

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.

Erik
  • 88,732
  • 13
  • 198
  • 189
  • "an entity that can be passed as a parameter, returned from a subroutine, or assigned into a variable." You are correct, but this is confusing. I think you need to make a distinction between class definition and class instantiation. Additionally, you're not quite answering the question. Why not make classes first-class objects and thus give this ability? It's like asking: "why couldn't C-strings be double-backslash-terminated?" and you answer: "because they must be NULL-terminated." – San Jacinto Mar 15 '11 at 13:46
  • @San Jacinto: The reason for lack of virtual constructors is that a virtual constructor would not make sense within c++'s design, specifically the "classes are not first class objects" part. The reason for c++'s design to be what it is would require a book or two :) – Erik Mar 15 '11 at 13:52
0

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();
}
CashCow
  • 30,981
  • 5
  • 61
  • 92
  • It'd work fine if c++ classes *were* first class objects, like classes are in many languages – Erik Mar 15 '11 at 13:41