• -There is no such thing as a virtual constructor in C++ simply because you need to know the exact type of the object you want to create and virtual represent the exact opposite concept
  • - But using an indirect way to create objects represents what is known as "Virtual Constructor Idiom". For example you could implement a clone() function as an indirect copy constructor or a create() member function as an indirect default constructor
  • - The GoF calls a variant of this idiom the Factory Method Pattern - "define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses". A concrete example will speak for itself:


Code:
// Product
class Page
{
};

// ConcreteProduct
class SkillsPage : public Page
{
};

// ConcreteProduct
class ExperiencePage : public Page
{
};

// ConcreteProduct
class IntroductionPage : public Page
{
};

// ConcreteProduct
class TableOfContentsPage : public Page
{
};

// Creator
class Document
{
// Constructor calls abstract Factory method
public:
    Document();

    // Factory Method
    virtual void CreatePages() { };
protected:
    std::list<Page*> thePageList;
};

Document :: Document()
{
    CreatePages();
};

// ConcreteCreator
class Resume : public Document
{
public:
    // Factory Method implementation
    void CreatePages();
};

// Factory Method implementation
void Resume :: CreatePages()
{
    thePageList.push_back(new SkillsPage());
    thePageList.push_back(new ExperiencePage());
}

// ConcreteCreator
class Report : public Document
{
public:
    // Factory Method implementation
    void CreatePages();
};

// Factory Method implementation
void Report :: CreatePages()
{
    thePageList.push_back(new TableOfContentsPage());
    thePageList.push_back(new IntroductionPage());
}

int main(int argc, char* argv[])
{
    // Note: constructors call Factory Method
    vector<Document*> documents(2);
    documents[0] = new Resume();
    documents[1] = new Report();

    return 0;
}