[C/C++] Use instanciate-function(factory function) to hide concreate class…

C++ doesn’t support the ‘interface’ explicitly unlike Java. So, combination of abstract class and virtual function, is used.
Let’s think of following case.

  A : pure abstract class (interface class).
  AImpl : implementation(concrete) class inherited from A.

External module that want to use ModuleA need to know interface, but don’t need to know it’s implementation. So, Knowing class A should be enough to use ModuleA. And this is tightly coupled with the way of instanciation.
Let’s see below

A* instance = new AImpl(argument);

This is easy way. But, in this case, definition of ‘AImpl’ should be included in external code. This is not good in terms of ‘Information Hiding’. We want to hide implementation details (even if it’s header). See following example to do this.

----- A.h
class A // interface class
    virtual ~A(){};
    static A* Create_instance(Arguments);
    int Interface_function_A(void) = 0;
    int Interface_function_B(void) = 0;

---- AImpl.h
#include "A.h"
class AImpl : private A
    friend class A;

---- A.cpp
#include "AImpl.h"
    AImpl* instance = new AImpl(Arguments);
    return static_cast(instance);

Now, knowing definition of class A is enough to use this module. Therefore, implementation details are completely hidden. Besides, inheriting as ‘private’, can prevent module from unexpected usage (AImpl can be used only through A). Here is sample usage.

#include "A.h"
A* instance = A::Create_instance(Arguments);
delete instance;

We made function for create instance. But, we should make destroying instance be possible by ‘delete’ keyword. Because, in many cases, knowing instance’s concrete class at the moment of deleting it, is not necessary. And unifying interfaces to destroy instance (into using ‘delete’) is also good to read.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s