[[ blog 이사 과정에서 정확한 posting날짜가 분실됨. 년도와 분기 정도는 맞지 않을까? ]]

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.

ModuleA
  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 instantiation.
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
{
public:
    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"
A::Create_instance(Arguments)
{
    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.

+ Recent posts