Suppose there is a factory as below. I would like to know if it is possible not to include ObjectA.h and ObjectB.h.
directory structure
factory
|-----ObjectA
|-----ObjectB
Since I don't want to include the header file in the sub-directory, is there any way to do so? And if there is a new objectC, it does not need to modify the factory class. it will automatically create ObjectC if the type is "TypeC".
#include "ObjectA.h"
#include "ObjectB.h"
object* create(const string& type)
{
if (type == "typeA")
{
return new ObjectA();
}
else
{
return new ObjectB();
}
};
Yes, separate the implementation to an implementation file and only include the files there, providing solely the function prototype in the header.
To actually call new ObjectA();
and new ObjectB();
you have to include the definitions in the calling site.
//factory.h
object* create(const string& type);
//factory.cpp
#include "factory.h"
#include "ObjectA.h"
#include "ObjectB.h"
object* create(const string& type)
{
if (type == "typeA")
{
return new ObjectA();
}
else
{
return new ObjectB();
}
};