C++ – How to declare factory-like method in base class


I'm looking for solution of C++ class design problem. What I'm trying to achieve is having static method method in base class, which would return instances of objects of descendant types. The point is, some of them should be singletons. I'm writing it in VCL so there is possibility of using __properties, but I'd prefer pure C++ solutions.

class Base {
    static Base *Instance;
    static Base *New(void);
    virtual bool isSingleton(void) = 0;
Base::Instance = NULL;

class First : public Base { // singleton descendant
    bool isSingleton(void) { return true; }

class Second : public Base { // normal descendant
    bool isSingleton(void) { return false; }

Base *Base::New(void) {
  if (isSingleton())
    if (Instance != NULL)
      return Instance = new /* descendant constructor */;
      return Instance;
    return new /* descendant constructor */;

Arising problems:

  • how to declare static variable Instance, so it would be static in descendant classes
  • how to call descendant constructors in base class

I reckon it might be impossible to overcome these problems the way I planned it. If so, I'd like some advice on how to solve it in any other way.

Edit: some minor changes in code. I have missed few pointer marks in it.

Best Solution

Just to check we have our terminologies in synch - in my book, a factory class is a class instances of which can create instances of some other class or classes. The choice of which type of instance to create is based on the inputs the factory receives, or at least on something it can inspect. Heres's a very simple factory:

class A { ~virtual A() {} };   
class B : public A {};
class C : public A {};

class AFactory {
      A * Make( char c ) {
         if ( c == 'B' ) {
             return new B;
         else if ( c == 'C' ) { 
            return new C;
         else {
           throw "bad type";

If I were you I would start again, bearing this example and the following in mind:

  • factorioes do not have to be singletons
  • factories do not have to be static members
  • factories do not have to be members of the base class for the hierarchies they create
  • factory methods normally return a dynamically created object
  • factory methods normally return a pointer
  • factory methods need a way of deciding which class to create an instance of

I don't see why your factory needs reflection, which C++ does not in any case support in a meaningful way.