Class encapsulation and information hiding in C++ with Examples

Class encapsulation and information hiding

 Separation of the public interface and private implementation

Class encapsulation and information hiding:- From the previous introduction, it is known that C++ implements encapsulation through classes, and seals data and operations related to these data. Installed in a class, in other words, the role of the class is to encapsulate data and algorithms in abstract data types declared by users. In object-oriented programming, when declaring a class, generally all data is designated as private, making it We are isolated from the outside world. Specify the member functions that need to be called by the outside world as public. Although it cannot be accessed directly outside the class Private data members, but you can reference or even modify private data members by calling public member functions.

The outside world can only operate on private data in the class through public member functions. Therefore, the outside world and the object are unique The contact channel is to call a public member function. In this way, the connection between the class and the outside world is reduced to a minimum. public The member function is the public interface of the user-used classe or the external interface of the class. After declaring a class, the user’s main job is to implement the class mention by calling its public member functions. Functions (such as setting values ​​for data members, Display the value of the data member, process the data, etc.). these functions Is determined when the class is declared, users can use them and They should not be changed. In fact, users often don’t care

The details of the implementation of these functions, and only need to know which function can be called to get what results, and what functions can be achieved. can. Just like using a camera, you only need to know that you can press the shutter to take a picture, without knowing the details of its implementation. A matter of designers and manufacturers. The shutter of the camera is a public interface, and the user uses the shutter to achieve the purpose of taking pictures. But the structure and function of the camera cannot be changed. All parts that are not related to user operations are encapsulated in the chassis, and users cannot See, can’t touch, can’t change, this is the separation of interface and implementation. Operating data members through member functions is called the realization of the function of the class. In order to prevent users from arbitrarily modifying the public Use member functions to change the operations performed on the data, often preventing users from seeing the source code of public member functions, which is obviously more It cannot be modified, and the user can only access the object code of the public member function (visit this article for details).


You can see: Class The data being manipulated in is private, and the implementation details of the function of the class are hidden from the user. This implementation is called a private implementation (private implementation). This “separation of public interface and private implementation of the class” forms information concealment (information hiding). The user is exposed to the public interface, but cannot access the hidden data and implementation detail. One of the most basic principles of software engineering is to separate the interface from the implementation. Information concealment is a part of software engineering. Very important concept. its The benefits are:

(1) If you want to modify or expand the functions of a class, you only need to modify the related data members of the class and its related components. Member functions, parts of the program other than the class need not be modified. For example:

Note: Although the data members in the class have changed and the definition of the member function display has changed, the external The interface has not changed, the outside world still accesses the data in the class through the public display function. Any other part of the program No need to modify. Of course, the function of the class has changed. When the display of the stud object is called, the student’s learning is output. Number, name, age, and gender values.

It can be seen that when the interface is separated from the implementation (operation on data), as long as the interface of the class does not change, the private real The current modification will not cause modification of other parts of the program. For users, the change in the implementation method of the class will not affect The user’s operation, as long as the interface of the class remains unchanged. For example, a software developer wants to use a class library previously provided to customers For modification and upgrade, as long as the interface of the class remains unchanged, that is, the method for the user to call the member function (including the class of function parameters) Type and number) remain unchanged, the user’s program must be modified.

 (2) If you find errors in the reading and writing of data in the class during compilation, you do not need to check the entire program, only check the access in this class Ask the few member functions of these data. In this way, the design, modification and debugging of programs (especially large programs) appear convenient and simple.



Separation of class declaration and member function definition

 If a class is only used by one program, then the declaration of the class and the definition of member functions can be directly written in the program At the beginning, but if a class is used by multiple programs, the amount of repetitive work is very large and the efficiency is too low. In the development of object-oriented programs, the declaration of the class (including the declaration of the member function) is often placed in the specified header In the file, if the user wants to use this class, just include the relevant header file, and there is no need to write the class repeatedly in the program The statement in order to reduce the workload, save space and improve the efficiency of programming.

Since the class is included in the header file Declaration, so the class name can be used directly in the user’s program to determine Righteous object. Since the prototype declaration of the member function is included in the class body, these objects can be called in the program The public member function. Therefore, use the #include instruction to include the relevant class declaration header file in the program, and use It is possible to use these classes in the program. Therefore, it can be considered that the class declaration header file is the public Use interface.

In order to realize the information concealment described in the previous article and prevent users from seeing the details of the function execution, the definition is generally not put in the header file together with the class declaration, but in a file separately. Include member function definitions The file is the realization of the class (that is, the function of the class is realized by calling the member function). Please pay special attention: The header file provided only includes the declaration of the member function, not the definition of the member function. Class declaration and function definition They are put in two files separately.

Because the examples in this textbook are relatively simple, for the convenience of reading the program, the declaration of the class, the definition of the class member function and The main function is written in the same program. In fact, a C++ program is composed of 3 parts:

 (1) Sound-like The header file (with a suffix of .h or no suffix);

(2) Class implementation files (with a suffix of .cpp), including the definition of class member functions;

(3) The use file of the class (suffix is ​​.cpp), that is, the main file.

For example, you can write two files separately:

(1) Class declaration header file

(2) The file containing the definition of the class member function (ie the class implementation file) (The function is defined in this file)

(3) The main file. In order to form a complete source program, there should also be a source file including the main function: (Main function module)

This is a program consisting of 3 files, composed of two file modules: one is the main module main.cpp, and the other is student.cpp. The header file student. h is included in the main module. In precompilation, the header file student.h will be Replace the #include “student.h” line with the content. Please note: Since the header file student.h is placed in the user’s current directory Therefore, wrap the file name with double withdrawals (“student.h”) instead of angle brackets (<student.h>). This file will not be found when compiling.

The program can be compiled and linked according to the method of compiling and running a multi-file program. C++ compilation system Compile the two source files main.cpp and student.cpp respectively to obtain two target programs main.obj and student. obj, and then connect them with other system resources to form an executable file main, exe, see the below Figure .

Class encapsulation and information hiding

When the main function is executed, the display function in stud is called to output the value of each data member. This is just a program framework. The data members num, name and sex are included in the Student class, but they are not There are assignments to the data members in the stud object. Although the program can be compiled and run, the output value is unpredictable Knowing, meaningless. Readers are requested to make necessary supplements to the above program framework (you can add a pair of Set function for data member assignment). Some readers may consider such a question: if a class declaration is selected by different programs multiple times, each The source file containing the member function definition (such as student.cpp above) must be compiled for the second time.

Can this be improved? What? Indeed, it is not necessary to repeat the compilation every time, but only once. Put student.cpp to 1 The object file formed after the second compilation is saved, and later when needed, it can be called out directly with the object file of the main file. Connect the pieces. This is similar to using the functions in the library. This is also a benefit of not putting the definition of the member function in the header file. If the definition of the member function also put In the header file of the class declaration, then, not only can’t realize information concealment, but also in every program that uses these classes The member function definition must be compiled every time it is compiled, that is, the definition of the same member function will be repeated multiple times Compile.


Put the definition of the member function separately in another file and compile it separately, and you can achieve no repeated compilation. In actual work, a class declaration is not made into a header file, but a number of commonly used functions are similar The class declarations are gathered together to form a class library. There are two types of library: one is the standard library provided by the C++ compilation system; One is a user class library made by users according to their own needs, which is provided to themselves and Use by a person authorized by you Define the class library. In the program development work, the class library is very useful, it can reduce the user’s own access to classes and member functions. The workload defined by the row.

The class library includes two components:

(1) the class declaration header file;

(2) the definition of the compiled member function,

it is the target file. Users only need to load the class library into their own computer system (usually installed in the C++ compilation system ), and use the #include directive in the program to include the header file of the relevant class declaration into the program, you can To use these classes in the program.

This is similar to the method of using standard functions provided by the C++ system in the program. For example, the user is calling sin When function, you only need to include the header file that contains the declaration of this function into the program to call the library function without having to understand How the sin function is implemented (how the function value is calculated). Of course, the premise is that the system has installed standard functions Library. After the user source file is compiled, it is connected with the system library (which is the object file). Include the class declaration header file in the user program, and the class declaration header file becomes an effective method for users to use the class library. Public interface, users can use related classes only through header files. This header text is visible and accessible to users Any user who wants to use this class only needs to include this header file.

The separation of interface and implementation creates good conditions for software developers to provide users with class libraries. Developer Put the declarations of the various classes required by the user in different header files by class, and at the same time, the source text that contains the definition of member functions Compile the file to get the object code defined by the member function. Software vendors provide users with the implementation of these header files and classes The target code (the source code of the function definition is not provided). When users use the classes in the class library, they only need to add the relevant header files Included to In your own program, you can link the object code defined by the member function after compilation. User can see Header file Declaration and the prototype declaration of the member function, but the source code of the definition of the member function cannot be seen, let alone the modification The definition of member function protects the rights and interests of developers. Due to the emergence of class libraries, users can easily use the general or specialized accumulated in practice like using parts. The class used, which greatly reduces the workload of program design and effectively improves work efficiency.



Several terms in object-oriented programming

By the way, I will introduce a few terms in object-oriented programming: The member functions of the class reflect the behavior of the object. It is called “method” in object program theory. “Method” refers to the manipulation of data. A “method” corresponds to An operation. Obviously, only methods (member functions) that are declared as public can be activated by the outside world of the object. Outside is

Activate the relevant method by sending a “message”. The so-called “message” is actually a command, a Sentence to achieve. front stud.display(); It is a “message” sent to the object stud to notify the object stud to execute the display “method” (ie display function). The above statement involves 3 terms: object, method, and message. Stud is the object, display() is the square Method, calling a method of an object (such as “stud.display();”) is a message sent to the object, requiring the object to execute Perform an operation.

The object-oriented theory involves many new terms. Readers are advised not to be intimidated or stumped by it. In fact, from practical applications, The point of view is not complicated. The requirements and methods of studying applied courses and studying theoretical courses are different. On average For non-professional readers who are new to C++, they only need to have a general understanding of object-oriented concepts. The focus of learning It should be placed on mastering the actual application, especially not to fall into the “big ocean” of abstract terms at the beginning Don’t die grammatical details regardless of primary and secondary. To be further studied and used in the future, Will naturally go deeper To master.

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

Leave a Reply

%d bloggers like this: