How to separate hierarchical data and GUI? - c++

I heard that it is better to separate data and GUI. For examples, I have some data. It is hierarchical with abstract base and derived class for concrete types, like
class Data {};
class ConcreteDataA : public Data {};
class ConcreteDataB : public Data {};
And I also have its hierarchical GUI (for example dialog)
class DataDialog {};
class ConcreteDataADialog : public DataDialog {};
class ConcreteDataBDilaog : public DataDialog {};
And I want create a data dialog object from a data object. If the data object is ConcreteDataA, ConcreteDataADialog is created, if B, B dialog is created. There is an easy way to do it by adding a virtual function in class Data like
virtual DataDialog* CreateDialog()
But if I add this function in the data class. it seems to violate the data/GUI separation principle. The second way is to build a global CreateDialog function, and create dialogs according to the dynamic_cast type of data object. This way is also not good for many maual ifs. Any other way to implement it? Or in practice, the first way is also okay? Thanks a lot!
One of my friends told me to use reflection. I think this should work.

It seems that you're looking for an Abstract Factory.
An Abstract Factory is a design pattern in which different types of objects can be created depending on the argument. So in this example, the factory will create a ConcreteDataADialog or a ConcreteDataBDilaog depending on the type of the data.
Code sketch:
class DialogFactory {
public:
virtual Dialog* createDialog() = 0;
};
class ADialogFactory : public DialogFactory {
public:
Dialog* createDialog() {
return new ADialog();
}
};
class BDialogFactory : public DialogFactory {
public:
Dialog* createDialog() {
return new BDialog();
}
};
class Application {
Dialog* createSpecificDialog(Data data) {
if (data.isA()) {
return new ADialogFactory().createDialog();
} else {
return new BDialogFactory().createDialog();
}
}

Related

C++ Reusable module class design

I have many, many modules that can benefit from using the exact same design pattern and share common classes. On the individual component level, everything makes sense, classes can easily be extended. But when I try to tie them together into a common module object, it seems like a pattern that polymorphism wasn't meant for, and I am missing the right pattern or design.
Starting out with all the base classes, which all other classes will extend from. The Module is the glue and the problem. Module will contain methods that prevent code duplication, such as AddComponent.
// A physical interface (Ethernet, Bluetooth, etc)
class Interface {};
// A basic component
class Component {};
// An std::map wrapper for managing Components
class ComponentManager {};
// A place to store data
class Database {};
// A module to tie all things together
class Module {
public:
Interface interface;
ComponentManager manager;
Database db;
void AddComponent(Component& c) {
manager.AddComponent(c);
db.InsertComponent(c);
}
};
Everything is fine until we want to extend all or most of the classes and the Module as well.
class EthInterface : public Interface {}; // cool
class UdpClientComponent : public Component {}; // cool
class UdpClientDatabase : public Database {}; // cool
//class UdpClientComponentManager : public ComponentManager {}; // 90% of the time won't need it
class UdpClientModule : public Module {
public:
EthInterface interface; // how to get an EthInterface instead of Interface?
UdpClientDatabase db; // how to get a UdpClientDatabase instead of Database?
};
I am trying to understand what pattern or design or what to use here. I think templates might not be the right solution because I've simplified this example, and don't think templates with 5 or 6 Ts are good design. I don't really get how to design this using ptrs because then I am feeding the extended Module ptrs from the outside, and I want this to be self contained, so that people can just write UdpClientModule module and they get batteries included, so to speak.
This might be a kick in the dark, but maybe it will send you searching in a different direction... You could use templates, redefining Module to look something like this:
template <class IFC, class COMP, class CM, class DB> class Module {
public:
IFC interface;
CM manager;
DB db;
void AddComponent(COMP& c) {
manager.AddComponent(c);
db.InsertComponent(c);
}
};
But if you go that way you should make sure that IFC, COMP, CM and DB are derived from Interface, Component, ComponentManager and Database and for that you need concepts. I don't know about you, but that is a bit over my head, so I would go a different way:
class Module {
public:
Module(Interface &ifc, Database &_db) :
interface(ifc),
manager(), db(_db) {
}
void AddComponent(Component& c) {
manager.AddComponent(c);
db.InsertComponent(c);
}
private:
Interface &interface;
ComponentManager manager;
Database &db;
};
class UdpClientModule : public Module {
public:
UdpClientModule() :
Module(ethInterface, udpClientDb),
ethInterface(),
udpClientDb() {
}
private:
EthInterface ethInterface;
UdpClientDatabase udpClientdb;
};
It's still clumsy, but it at least gets you some of the way to where (I assume) you want to get.
Interfaces depends from abstraction, you want to depend from concrete types and there where your design flaw. Keep the interface to do the "interface" and leave the concrete classes dealing with the concrete types.
class Module {
public:
virtual ~Module() = default;
void AddComponent(Component& c) {
manager().AddComponent(c);
db().InsertComponent(c);
}
virtual Interface& interface() = 0;
virtual ComponentManager& manager() = 0;
virtual Database& db() = 0;
};
class UdpClientModule : public Module {
public:
Interface& interface() override { return ethInterface; }
ComponentManager& manager() override { return udcClienddb; }
Database& db() override { return manager; }
void specialUdpMethod() const { /*...*/}
private:
EthInterface ethInterface;
UdpClientDatabase udpClientdb;
ComponentManager manager;
};
In this case you're stating every module must provide an interface, e component manager and a db. If you have more relaxed constraint you could move the dependencies to a dependency injection solution and use pointer instead.

Functionality of a pure virtual function with variable return type - workaround/design?

I'm working on a very, very simple data access layer (DAL) featuring two classes: DataTransferObject (DTO) and DataAccessObject (DAO). Both classes are abstract base classes and need to be inherited and modified for a specific use case.
class DataTransferObject {
protected:
//protected constructor to prevent initialization
};
class DataAccessObject {
public:
virtual bool save(DataTransferObject o) = 0;
virtual DataTransferObject* load(int id) = 0;
};
in case of a House class from the business logic layer, the implementation of the DAL classes would read something along these lines:
class Dto_House : public DataTransferObject {
public:
int stories;
string address; //...which are all members of the House class...
Dto_House(House h);
};
class Dao_House : public DataAccessObject {
public:
bool save(Dto_House h) { /*...implement database access, etc...*/ }
Dto_House* load(int id) {/*...implement database access, etc...*/ }
};
EDIT: Of course, the derived classes know about the structure of the House class and the data storage.
Simple, nice, okidoke.
Now I wanted to provide a method toObject() in the DTO class in order to quickly convert the Dto_House into a House object. I then read about the automatic return type deduction in C++14 and tried:
class DataTransferObject {
public:
virtual auto toObject() = 0;
};
But I had to discover: No automatic return type deduction for virtual functions. :(
What are your ideas about implementing a "virtual function with deduced return type" for this specific case? I want a general toObject() function in my DTO "interface".
The only thing that came to my mind was something like:
template <typename T>
class DataTransferObject {
virtual T toObject() = 0;
};
class Dto_House : public DataTransferObject<House> {
public:
int stories;
string address;
House toObject() {return House(stories, address);}
};
EDIT:
A possible use case would be:
House h(3, "231 This Street");
h.doHouseStuff();
//save it
Dto_House dtoSave(h);
Dao_House dao;
dao.save(dtoSave); //even shorter: dao.save(Dto_House(h));
//now load some other house
Dto_House dtoLoad = dao.load(id 2);
h = dtoLoad.toObject();
h.doOtherHouseStuff();
But the house does not know it can be saved and loaded.
Of course, the abstract DAO class may be derived to further refine it for the use with, e.g. Sqlite, XML files or whatever... I just presented the very basic concept.
How about setting an empty abstract class - practically, an interface, then have both of your types implement it and set this as the toObject returning reference type?
class Transferable
{
virtual ~Transferable() = 0;
}
And then:
class DataTransferObject {
public:
//Return a reference of the object.
virtual Transferable& toObject() = 0;
};
Dto_House : public DataTransferObject, Transferable { /*...*/ }
House : public DataTransferObject, Transferable { /*...*/ }
The example above is to get my point.
Even better, you can use the DataTransferObject for this cause as your returning reference type, and no other abstract class:
class DataTransferObject {
public:
virtual DataTransferObject& toObject() = 0;
};
Dto_House : public DataTransferObject { /*...*/ }
House : public DataTransferObject { /*...*/ }
Update: If you want to have the classes separated apart, separating any association between data and operations by convention, you could set the name of the base class on something that represents the data i.e.: Building, Construction etc, and then use it for the reference type in toObject.
You can also have the class manipulating those operations on the API of data manipulation.
In general, you can not have a virtual function returning different types in different subclasses, as this violates the whole concept of statically typed language: if you call DataTransferObject::toObject(), the compiler does not know what type it is going to return until runtime.
And this highlight the main problem of your design: why do you need a base class at all? How are you going to use it? Calling DataTransferObject::toObject(), even if you use some magic to get it work (or use a dynamically typed language), sounds like a bad idea since you can not be sure what the return type is. You will anyway need some casts, or some ifs, etc, to get it working — or you will be using only the functionality common for all such objects (House, Road, etc.) — but then you just need a common base class for all of them.
In fact, there is one exception to the same return type rule: if you return a pointer to a class, you can use the Covariant return type concept: a subclass may override a virtual function to return a subclass of the original return type. If all your "objects" have a common base class, you may use something along the lines of
struct DataTransferObject {
virtual BaseObject* toObject() = 0;
};
struct Dto_House : public DataTransferObject {
virtual House* toObject() { /*...*/ } // assumes that House subclasses BaseObject
};
However, this will still leave the same problem: if all you have in your code is DataTransferObject, even if you (but not the compiler) know it is a Dto_House, you will need some cast, which might be unreliable.
On the other hand, you template solution seems quite good except that you will not be able to explicitly call DataTransferObject::toObject() (unless you know the type of the object), but that's a bad idea as I have explained.
So, I suggest you think on how you are going to actually use the base classes (even write some sample code), and make your choice based on that.

Instantiation of class by classname

I have multiple classes that share a common base class, like this:
class Base {};
class DerivedA : public Base {};
class DerivedB : public Base {};
class DerivedC : public Base {};
Now, I need to know which of these derived classes to instantiate during runtime (based on input). For example, if input is "DerivedA", I need to create a DerivedA object. The input is not necessarily a string, it could be an integer as well - the point is that there is a key of some sort and I need a value to match the key.
The problem is, though, how do I instantiate the class? C++ does not have built-in reflection like C# or Java. A commonly suggested solution I've found is to use a factory method like this:
Base* create(const std::string& name) {
if(name == "DerivedA") return new DerivedA();
if(name == "DerivedB") return new DerivedB();
if(name == "DerivedC") return new DerivedC();
}
This would be sufficient if there's only a couple of classes, but becomes cumbersome and probably slow if there's tens or hundreds of derived classes. I could quite easily automate the map creation process to produce a std::map<std::string, ***>, but I have no idea what to store as the value. AFAIK, pointers to constructors are not allowed. Again, if I do a factory using this map, I'd still need to write a factory method for each type, making it even more cumbersome than the example above.
What would be an efficient way to handle this problem, especially when there's lots of derived classes?
You can always store std::function<Base*()> as you always return pointers to Base from your create function:
class Base {};
class DerivedA : public Base {};
class DerivedB : public Base {};
class DerivedC : public Base {};
Base* create(const std::string& type)
{
static std::map<std::string, std::function<Base*()>> type_creator_map =
{
{"DerivedA", [](){return new DerivedA();}},
{"DerivedB", [](){return new DerivedB();}},
{"DerivedC", [](){return new DerivedC();}}
};
auto it = type_creator_map.find(type);
if(it != type_creator_map.end())
{
return it->second();
}
return nullptr;
}
As Angew suggested, you should return std::unique_ptr instead of raw pointers. If the user of create function wants a raw pointer or a std::shared_ptr he/she can just "grab" the raw pointer and use it.
UPDATE:
Next method provides a convenient semi-automatic way of registering new types without changing old code.
I don't recommend using it because it depends on the linker (the moment of creating global variables might be delayed), they way you compile the code(executable, static library, dynamic library), it allocates memory before main() starts and it creates weird named global variables.
Use it only if you really know what you are doing and know on what platforms you are using the code!
class Base {};
std::map<std::string, std::function<Base*()>>& get_type_creator_map()
{
static std::map<std::string, std::function<Base*()>> type_creator_map;
return type_creator_map;
}
template<typename T>
struct RegisterTypeHelper
{
RegisterTypeHelper(const std::string& id)
{
get_type_creator_map()[id] = [](){return new T();};
}
};
Base* create(const std::string& type)
{
auto& type_creator_map = get_type_creator_map();
auto it = type_creator_map.find(type);
if(it != type_creator_map.end())
{
return it->second();
}
return nullptr;
}
#define RegisterType(Type) static RegisterTypeHelper<Type> register_type_global_##Type(#Type)
class DerivedA : public Base {};
RegisterType(DerivedA);
class DerivedB : public Base {};
RegisterType(DerivedB);
class DerivedC : public Base {};
RegisterType(DerivedC);
One way to solve this is to use the design pattern Prototype.
Basically, you wouldn't create the derived class objects by direct initialisation, but by cloning a prototype instead. Your create() function is actually a realisation of the Factory method design pattern. You can use Prototype inside the implementation, like this:
class Base
{
public:
virtual ~Base() {}
virtual Base* clone() = 0;
};
class DerivedA : public Base
{
public:
virtual DerivedA* clone() override { return new DerivedA; }
};
Base* create(const std::string &name)
{
static std::map<std::string, Base*> prototypes {
{ "DerivedA", new DerivedA },
{ "DerivedB", new DerivedB },
{ "DerivedC", new DerivedC }
};
return prototypes[name]->clone();
}
Error checking left out of the example for brevity.
In a real project, you should of course use a smart pointer (such as std::unique_ptr) instead of raw pointers to manage the objects' lifetimes.
I could quite easily automate the map creation process to produce a std::map, but I have no idea what to store as the value.
You need to store a factory method as the value, e.g. a static method which creates an instance of your class:
class Base {};
class DerivedA : public Base {
public:
static Base* create();
...
}
...
Base* DerivedA::create() {
return new DerivedA();
}
You can then implement the name/lookup through a map like
typedef Base* (*FACTORY_FUNCTION)();
std::map<std::string, FACTORY_FUNCTION> factories;
...
factories["ClassA"] = ClassA::create;
if I do a factory using this map, I'd still need to write a factory method for each type
Since these factory methods are very simple, you can automate their creation by a simple code generation tool (e.g. with a simple shell script). You can either maintain a list of classes, or retrieve this list from your header files (e.g. by grepping for the class keyword and retrieve the succeeding class name, or even better by using some analysis tool which properly parses the header files).
With that information, you can automatically create the necessary code to automatically add the factory methods to each class. With the same approach, you could also generate the registration function which needs to be called once, so that your objects are getting registered.

Access to 'inner' classes in case of composition

I have certain functionality encapsulated in classes which I use in another class. I think this is called composition.
class DoesSomething01
{
public:
DoesSomething01();
void functionality01();
void functionality02();
};
class DoesSomething02
{
public:
DoesSomething02();
void functionality01();
void functionality02();
};
class ClassA
{
public:
ClassA();
private:
DoesSomething01 *m_doesSomething01;
DoesSomething02 *m_doesSomething02;
};
If I have now a ClassB which "knows" ClassA and have to use/execute functionality01 and/or functionality02 of classes DoesSomething01 and/or DoesSomething02 I see two possibilities:
a) Add methods like this to ClassA to provide ClassB direct access to DoesSomething01 and/or DoesSomething02:
DoesSomething01 *getDoesSomething01() { return *m_doesSomething01; }
DoesSomething02 *getDoesSomething02() { return *m_doesSomething02; }
ClassB could then do something like this:
m_classA->getDoesSomething01()->functionality01();
b) Add (in this case four) methods to ClassA which forwards the method calls to DoesSomething01 and DoesSomething02 like this:
void doesSomething01Functionality01() { m_doesSomething01->functionality01(); }
void doesSomething01Functionality02() { m_doesSomething01->functionality02(); }
void doesSomething02Functionality01() { m_doesSomething02->functionality01(); }
void doesSomething02Functionality02() { m_doesSomething02->functionality02(); }
Which option is better and why?
What are the advantages/disadvantages of each option?
First option can be considered a code smell. According to Robert C. Martin's 'Clean Code' it is "Transitive Navigation" and should be avoided. Quoting the author:
In general we don’t want a single module to know much about its
collaborators. More specifically, if A collaborates with B, and B
collaborates with C, we don’t want modules that use A to know about C.
(For example, we don’t want a.getB().getC().doSomething();.)
Second option looks better. It is classical use of Facade pattern. And it is better, because it hides other functionalities of classes DoesSomthing01 and DoesSomthing02. Then you ve'got simplified view of it which is easier to use than 1st option.
Edit: there is also one more thing. You've got two classes which have the same functionalites and are aggregated by other class. You should consider using Stratey pattern here. The your code will look like this:
class DoesSomething
{
public:
virtual void functionality01() = 0;
virtual void functionality02() = 0;
}
class DoesSomething01 : DoesSomething
{
public:
DoesSomething01();
void functionality01();
void functionality02();
};
class DoesSomething02 : DoesSomething
{
public:
DoesSomething02();
void functionality01();
void functionality02();
};
class ClassA
{
public:
ClassA();
DoesSomething* doesSomething(); // Getter
void doesSomething(DoesSomething* newDoesSomething); // Setter
// ...
private:
DoesSomething *m_doesSomething;
};
Then you will need only two method instead of four:
void doesFunctionality01() { m_doesSomething->functionality01(); }
void doesFunctionality02() { m_doesSomething->functionality02(); }
The first scenario is a violation of law of Demeter, which says that a class can only talk to its immediate friends. Basically the problem with the first approach is that any change in the inner classes DoSomething01 and DoSomething02 will trigger a change in Class A as well as Class B because both classes are now directly dependent on these inner classes.
The second option is better as it encapsulates the class B from inner classes but a side effect of this solution is that now class A has a lot of methods that does nothing fancy except for delegating to its inner classes. This is fine but imagine if DoSomething01 has an inner class DoSomething03 and class B needs to access its functionality without directly knowing about it than the class A would need to have another method that would delegate to DoSomething01 that would in turn delegate to DoSomething03. In this case I think it is better to let class B directly know about DoSomething01 otherwise class A is going to have a huge interface that simply delegates to its inner classes.
If there are many classes and/or many methods to be called it makes sense to invent
an interface in the form of an abstract parent class:
class SomeInterface
{
public:
SomeInterface(){}
virtual void functionally01() = 0;
virtual void functionally02() = 0;
}
DoesSomthing01 and other classes would then inherit this class:
class DoesSomthing01 : public SomeInterface
and implement the methods.
If it make sense to associate a key with the instantiation of such a class
you could store these objects in ClassA e.g. using a map (here I
use an integer as the key):
class ClassA
{
private:
std::map<int, SomeInterface*> m_Interfaces;
public:
SomeInterface* getInterface(const int key)
{
std::map<int, SomeInterface*>::iterator it(m_Interfaces.find(key));
if (it != m_Interfaces.end())
return it->second;
else
return NULL;
}
};
From ClassB you could then access them
int somekey = ...;
SomeInterface *myInter = m_classA->getInterface(somekey);
if (myInter)
myInter->functionally01();
This way you have just one access method (getInterface()) independent
of the number of objects.
In order to encode the access to the methods using a key you could
create a map which maps a key onto a closure or a simple switch statement:
in SomeInterface:
public:
void executeMethod(const int key)
{
switch(key)
{
case 1: functionally01(); break;
case 2: functionally01(); break;
default:
// error
}
int methodKey = ...;
int objectKey = ...;
SomeInterface *myInter = m_classA->getInterface(objectKey);
if (myInter)
myInter->executeMethod(methodKey);
Looks like a good case for a Mediator Pattern.
This pattern manage communication between 2 objects that he owns.

Registering derived classes in C++

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.
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.
Usually, base class/ derived class pattern is used when you have an interface in base class, and that interface is implemented in derived class (IS-A relationship). In your case, the base class does not seem to have any connection with derived class - it may as well be void*.
If there is no connection between base class and derived class, why do you use inheritance? What is the benefit of having a factory if factory's output cannot be used in a general way? You have
class CAbstractFactory
{
public:
virtual ~CAbstractFactory()=0;
};
This is perfectly wrong. A factory has to manufacture something that can be used immediately:
class CAbstractFactory
{
public:
virtual ~CAbstractFactory(){};
public:
CBaseClass* CreateAndGet()
{
pClass = new Class;
return pClass;
}
private:
CBaseClass* pClass;
protected:
CBaseClass *create() = 0;
};
In general, you're mixing inheritance, virtual functions and templates the way they should not be mixed.
Without having read all of the code or gone into the details, it seems like you should've done the following:
make b of type CChildClass,
make CBaseClass::Print a virtual function.
Maybe I'm wrong but I didn't find any return statement in your CBaseClass::Create() method!
Personally, I think this design overuses inheritance.
"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." - I don't know that IS-A relationships should be that flexible.
I wonder if you'd be better off using interfaces (pure virtual classes in C++) and mixin behavior. If I were writing it in Java I'd do this:
public interface Foo
{
void doSomething();
}
public class MixinDemo implements Foo
{
private Foo mixin;
public MixinDemo(Foo f)
{
this.mixin = f;
}
public void doSomething() { this.mixin.doSomething(); }
}
Now I can change the behavior as needed by changing the Foo implementation that I pass to the MixinDemo.