C and C++ three types of information hiding implemented in program development

  • 2020-05-09 18:52:59
  • OfStack

Whether it is modular design, object-oriented design, or layered design, the realization of the subsystem internal information hiding is the most critical internal requirements. According to my simple experience, the information hiding is divided into (1) invisible and unavailable, (2) visible and unavailable, and (3) visible and available.

1 is not visible and not available

That is, the variables, structs, and class definitions inside the module are completely hidden from the outside, and the outside knows nothing about 1. A common way to do this is to use opaque Pointers. See my blog post on how to use opaque Pointers to hide structure details when developing libraries in C.

This approach also applies to the C++ language, one possible implementation of which is interface-oriented programming.

The header file IMyClass h


class IMyClass
{
public:
virtual ~IMyClass();
public:
virtual void public_function1();
virtual void public_function2();
};
IMyClass* CreateMyClassObject();

Implementation file MyClass.cpp


#include "IMyClass.h"
class MyClass : IMyClass.h
{
private:
int x;
int y;
int z;
public:
virtual void public_function1();
virtual void public_function2();
};
IMyClass* CreateMyClassObject()
{
return new MyClass();
}

This implementation works at both the source and library levels.

In theory, complete invisibility is the perfect design. However, this is very demanding for programming, and can result in more code and design logic levels, as well as some limitations (such as the inability to implement inheritance of existing types).

As a result, many C++ libraries are designed in such a way that they can be seen and not used, such as MFC.

2 is not available

This method refers specifically to C++, which refers to the non-public type members of the C++ class. For example, in the header file myclass.h:


class MyClass
{
private:
int x;
int y;
int z;
protected:
float f;
public:
int M;
void member_method1();
};

For callers, including subheader files, you can see x,y,z and other member variables, but you can't use them. As long as the client needs to use new to generate an instance or an inherited class, it must know the full definition of the class.

With the C language, this is not the case because any variables in the structure are exposed.

3 visible and available

That is, there is no hiding in terms of programming absolutely to avoid.

The above is for C/C++ program development to achieve the three types of information hiding, I hope to help you!


Related articles: