Three types of information hiding in C/C ++ Program Development
Whether it is modular design, object-oriented design, or hierarchical design, it is the most critical internal requirement to realize external hiding of internal information of the subsystem. Based on my own simple experience, we can hide information into (1) invisible unavailable (2) Visible unavailable (3) Visible and available.
1 invisible unavailable
That is to say, the internal variables, struct, and class definitions of the module are completely hidden from the outside, and the outside knows nothing about this. The common implementation method is to use an opaque pointer. For more information, see the C language development function of my blog post to hide the structure details with an opaque pointer.
This method is also applicable to the C ++ language. One possible implementation method is interface-oriented programming.
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 method can be applied at both the source code level and the database level.
Theoretically, completely invisible is the perfect design. However, this requires a lot of programming, and brings more code, design logic levels, and some restrictions (such as the inability to inherit existing types ).
Therefore, many C ++ libraries adopt the following visible and unavailable methods, such as MFC.
2 visible unavailable
This method refers to the non-public type member in 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();};
After the sub-header file is included, the caller cannot use the x, y, z, and other member variables. As long as the client needs to use new to generate an instance or inherit a class, the complete definition of the class must be known.
This is not the case for C, because any variable in the struct is public.
3 visible
That is to say, the program design must be avoided without hiding it.