Listing 2: Demonstrates use of macros to make traditional approach to creating class factories easier

// file Clsfctry.h

#ifndef CLSFCTRY_H
#define CLSFCTRY_H

using namespace std;

#define CLASSFACTORYCREATE(CLASS, ID)  \
   if (!strcmp(ClassID, ID)) return new CLASS;

#define CLASSFACTORYBASE(CLASS) \
   CLASS *Create(const char *ClassID);

#define BEGINCLASSFACTORYMAP(CLASS) \
   CLASS *CLASS::Create(const char *ClassID) {

#define ENDCLASSFACTORYMAP return 0;}

class MyBaseFactoryItem
{
public:
   MyBaseFactoryItem() {};
   virtual ~MyBaseFactoryItem() {};
   CLASSFACTORYBASE(MyBaseFactoryItem);
};

class MyFactoryItemOne : 
   public MyBaseFactoryItem
{
public:
   MyFactoryItemOne() 
   {cout << "One" << endl;};
   virtual ~MyFactoryItemOne() {};
};

class MyFactoryItemTwo : 
   public MyBaseFactoryItem
{
public:
   MyFactoryItemTwo() 
   {cout << "Two" << endl;};
   virtual ~MyFactoryItemTwo() {};
};

#endif

// file Clsfctry.cpp

#include "stdafx.h"
#include "clsfctry.h"

BEGINCLASSFACTORYMAP(MyBaseFactoryItem)
  CLASSFACTORYCREATE(MyFactoryItemOne, "One");
  CLASSFACTORYCREATE(MyFactoryItemTwo, "Two");
ENDCLASSFACTORYMAP

— End of Listing —