C++ – Registering derived classes in C++

abstract-classc++design-patternsfactorytemplates

EDIT: minor fixes (virtual Print; return mpInstance) following remarks in the answers.

I am trying to create a system in which I can derive a Child class from any Base class, and its implementation should replace the implementation of the base class.

All the objects that create and use the base class objects shouldn't change the way they create or call an object, i.e. should continue calling BaseClass.Create() even when they actually create a Child class.
The Base classes know that they can be overridden, but they do not know the concrete classes that override them.

And I want the registration of all the the Child classes to be done just in one place.

Here is my implementation:

class CAbstractFactory
{
public:
    virtual ~CAbstractFactory()=0;
};

template<typename Class>
class CRegisteredClassFactory: public CAbstractFactory
{
public:
    ~CRegisteredClassFactory(){};
    Class* CreateAndGet()
    {
        pClass = new Class;
        return pClass;
    }
private:
    Class* pClass;
};

// holds info about all the classes that were registered to be overridden
class CRegisteredClasses
{
public:
    bool find(const string & sClassName);
    CAbstractFactory* GetFactory(const string & sClassName)
    {
        return mRegisteredClasses[sClassName];
    }
    void RegisterClass(const string & sClassName, CAbstractFactory* pConcreteFactory);
private:
    map<string, CAbstractFactory* > mRegisteredClasses;

};


// Here I hold the data about all the registered classes. I hold statically one object of this class.
// in this example I register a class CChildClass, which will override the implementation of CBaseClass, 
// and a class CFooChildClass which will override CFooBaseClass
class RegistrationData
{
    public:
        void RegisterAll()
        {
            mRegisteredClasses.RegisterClass("CBaseClass", & mChildClassFactory);
            mRegisteredClasses.RegisterClass("CFooBaseClass", & mFooChildClassFactory);
        };
        CRegisteredClasses* GetRegisteredClasses(){return &mRegisteredClasses;};
    private:    
        CRegisteredClasses mRegisteredClasses;
        CRegisteredClassFactory<CChildClass> mChildClassFactory;
        CRegisteredClassFactory<CFooChildClass> mFooChildClassFactory;
};

static RegistrationData StaticRegistrationData;

// and here are the base class and the child class 
// in the implementation of CBaseClass::Create I check, whether it should be overridden by another class.
class CBaseClass
{
public:
    static CBaseClass* Create()
    {
        CRegisteredClasses* pRegisteredClasses = StaticRegistrationData.GetRegisteredClasses();
        if (pRegisteredClasses->find("CBaseClass"))
        {
            CRegisteredClassFactory<CBaseClass>* pFac = 
                dynamic_cast<CRegisteredClassFactory<CBaseClass>* >(pRegisteredClasses->GetFactory("CBaseClass"));

            mpInstance = pFac->CreateAndGet();
        }
        else
        {
            mpInstance = new CBaseClass;
        }
        return mpInstance;
    }
    virtual void Print(){cout << "Base" << endl;};
private:
    static CBaseClass* mpInstance;

};

class CChildClass : public CBaseClass
{
public:
    void Print(){cout << "Child" << endl;};
private:

};

Using this implementation, when I am doing this from some other class:

StaticRegistrationData.RegisterAll();
CBaseClass* b = CBaseClass::Create();
b.Print();

I expect to get "Child" in the output.

What do you think of this design? Did I complicate things too much and it can be done easier? And is it OK that I create a template that inherits from an abstract class?

I had to use dynamic_pointer (didn't compile otherwise) – is it a hint that something is wrong?

Thank you.

Best Solution

This sort of pattern is fairly common. I'm not a C++ expert but in Java you see this everywhere. The dynamic cast appears to be necessary because the compiler can't tell what kind of factory you've stored in the map. To my knowledge there isn't much you can do about that with the current design. It would help to know how these objects are meant to be used. Let me give you an example of how a similar task is accomplished in Java's database library (JDBC):

The system has a DriverManager which knows about JDBC drivers. The drivers have to be registered somehow (the details aren't important); once registered whenever you ask for a database connection you get a Connection object. Normally this object will be an OracleConnection or an MSSQLConnection or something similar, but the client code only sees "Connection". To get a Statement object you say connection.prepareStatement, which returns an object of type PreparedStatement; except that it's really an OraclePreparedStatement or MSSQLPreparedStatement. This is transparent to the client because the factory for Statements is in the Connection, and the factory for Connections is in the DriverManager.

If your classes are similarly related you may want to have a function that returns a specific type of class, much like DriverManager's getConnection method returns a Connection. No casting required.

The other approach you may want to consider is using a factory that has a factory-method for each specific class you need. Then you only need one factory-factory to get an instance of the Factory. Sample (sorry if this isn't proper C++):

class CClassFactory
{
  public:
    virtual CBaseClass* CreateBase() { return new CBaseClass(); }
    virtual CFooBaseClass* CreateFoo() { return new CFooBaseClass();}
}

class CAImplClassFactory : public CClassFactory
{
  public:
    virtual CBaseClass* CreateBase() { return new CAImplBaseClass(); }
    virtual CFooBaseClass* CreateFoo() { return new CAImplFooBaseClass();}
}

class CBImplClassFactory : public CClassFactory // only overrides one method
{
  public:
    virtual CBaseClass* CreateBase() { return new CBImplBaseClass(); }
}

As for the other comments criticizing the use of inheritance: in my opinion there is no difference between an interface and public inheritance; so go ahead and use classes instead of interfaces wherever it makes sense. Pure Interfaces may be more flexible in the long run but maybe not. Without more details about your class hierarchy it's impossible to say.

Related Question