Class encapsulation and information hiding in C++ with Examples
Table of Contents
Separation of public interface and private implementation
From the previous presentation, it is realized that C++ implements encapsulation through classes, and seals data and operations identified with these data Installed in a class, at the end of the day, the function of the class is to encapsulate data and algorithms in abstract data types declared by users. In object-oriented programming, while declaring a class, by and large all data is designated as private, making it we are isolated from the outside world. Specify the member functions that should be called by the outside world as open. Despite the fact that it can’t be accessed straightforwardly outside the class Private data members, however you can reference or even adjust private data members by calling public member functions.
The outside world can just work on private data in the class through open member functions. Along these lines, the outside world and the object are novel the contact channel is to call a public member function. In this manner, the connection between the class and the outside world is diminished to a base. The member function is the public interface of the user-used class or the external interface of the class. Subsequent to declaring a class, the user’s principle work is to actualize the class notice by calling its public member functions. Functions (such as setting values for data members, Display the estimation of the data member, process the data, and so forth) these functions are resolved when the class is declared, users can use them and they should not be changed.
Indeed, users frequently couldn’t care, just like using a camera; you just need to realize that you can press the shutter to snap a photo, without knowing the details of its usage. The shutter of the camera is a public interface, and the user uses the shutter to accomplish the purpose of taking pictures. However, the structure and function of the camera can’t be changed. All parts that are not identified with user operations are encapsulated in the chassis, and users can’t see, can’t contact, can’t change, this is the separation of interface and execution. Working data members through the member function is known as the realization of the function of the class. To keep users from subjectively adjusting the public user member functions to change the operations performed on the data, routinely shielding users from seeing the source code of public member functions, which is unmistakably more It can’t be modified, and the user can just access the object code of the public member function.
You can see: Class The data being manipulated 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 the public interface and private implementation of the class” form information concealment (information hiding). The user is presented to the public interface, yet can’t access the hidden data and implementation detail. One of the most essential standards of programming designing is to isolate the interface from the implementation. Data concealment is a piece of programming designing important idea. The advantages are:
(1) If you need to alter or extend the functions of a class, you just need to change the connected data members of the class and its connected components. Member functions, parts of the program other than the class need not be altered. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Student { private: int num; string name; int age; char sex; public: void display { cout << "num:" << num << endl; cout << "name:" << name << endl; cout << "age:"<< age << endl; cout << "sex:"<< sex << endl; } |
Note: Although the data members in the class have changed and the definition of the member function display has changed, the external interface has not changed, the outside world still accesses the data in the class through the public display function. Some other piece of the program No compelling reason to change. Of course, the function of the class has changed. At the point when the display of the stud object is called, the student’s learning is output. Number, name, age, and gender values.
It tends to 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 alteration won’t cause adjustment of different parts of the program. For users, the adjustment in the implementation method of the class won’t influence the user’s operation, as long as the interface of the class remains unaltered. For instance, a software developer wants to use a class library previously gave to customers To change and redesign, as long as the interface of the class remains unaltered, that is, the method for the user to call the member function (counting the class of function parameters) Type and number) stay unaltered, the user’s program must be adjusted.
(2) If you discover errors in the reading and writing of data in the class during compilation, you don’t have to check the whole program, just check the access in this class ask the couple of member functions of these data. In this manner, the design, adjustment and debugging of programs (especially huge programs) seem advantageous and simple.
Separation of class declaration and member function definition
In the event that a class is just used by one program, at that point the statement of the class and the definition of member functions can be legitimately written in the program
In the beginning, yet in the event that a class is used by numerous programs, the amount of dreary work is extremely huge and the effectiveness is excessively low. In the advancement of object-oriented programs, the declaration of the class (including the declaration of the member function) is regularly positioned in the specified header In the file, if the user wants to use this class, just include the important header file, and there is no compelling reason to compose the class over and over in the program. The statement to diminish the workload, save space and improve the proficiency of programming. Since the class is included in the header file Declaration, so the class name can be used straightforwardly in the user’s program to decide the Righteous object. Since the prototype declaration of the member function is included in the class body, these objects can be brought in the program the public member function. In this manner, use the #include instruction to include the significant class declaration header file in the program, and It is possible to use these classes in the program. Hence, it tends to be considered that the class declaration header file is the public User interface.
To realize the data concealment described in the previous section and keep users from seeing the details of the function execution, the definition is commonly not placed in the header file along with the class declaration, yet 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 give special consideration: The header file gave just includes the declaration of the member function, not the definition of the member function. Class declaration and function definition they are placed in two files separately.
Because the examples in this article are moderately simple, for the accommodation 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. Truth be told, 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
1 2 3 4 5 6 7 8 9 10 11 12 |
student.h // (1) Class declaration header file (This is a header file named student.h, where the class declaration is made) #include <string> using namespace std; class Student { //Class declaration public: void display(); private: int num; string name; //Public member function prototype declaration char sex; }; |
1 2 3 4 5 6 7 8 9 10 |
student.cpp //(2) The file containing the definition of the class member function (ie the class implementation file) (The function is defined in this file) #include <iostream> #include "student.h" void Student display () { cout << "num:" << num << endl; cout << "name:" << name << endl; cout << "sex:" << sex << endl; } |
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)
//main.cpp
1 2 3 4 5 6 7 8 9 |
#include <iostream> #include "student.h" //Include the class declaration file using namespace std; int main() { Student stud; //Define the object stud stud.display(); //Execute the display function of the stud object return 0; } |
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 replaced the #include “student.h” line with the content. Please note: Since the header file student.h is put in the user’s current directory. Therefore, wrap the file name with double quotes (“student.h”) instead of angle brackets (<student.h>). This file won’t be discovered when compiling.
The program can be compiled and linked by 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 acquire two target programs main.obj and student. obj, and afterward connect them with other system resources to shape an executable file main.exe, see the beneath Figure .
At the point when the main function is executed, the display function in stud is called to output the value of every data member. This is just a program framework. The data members num, name and sex are included in the Student class, however they are not their assignments to the data members in the stud object. In spite of the fact that the program can be compiled and run, the output value is erratic Knowing, meaningless. Readers are requested to make necessary supplements to the above program framework (you can add a couple of Set functions for data member assignment). Some readers may consider such a question: if a class declaration is selected by various programs multiple times, each
The source file containing the member function definition (such as student.cpp above) must be compiled for the second time. Would this be able to be improved? What? Undoubtedly, it is not necessary to repeat the compilation without fail, but rather just a single time. Put student.cpp to 1 the object file shaped after the second compilation is saved, and later when required, it very well may be called out straightforwardly with the object file of the main file. Connect the pieces. This is similar to using the functions in the library. This is also an advantage of not putting the definition of the member function in the header file. In the event that the definition of the member function also put In the header file of the class declaration, at that point, can’t realize data concealment, yet in addition in each program that uses these classes The member function definition must be compiled each 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 gather it separately and you can accomplish no rehashed compilation. In real work, a class declaration is not made into a header file, however a number of ordinarily used functions are similar the class declarations are assembled to shape a class library. There are two types of library: one is the standard library gave by the C++ compilation system; One is a user class library made by users as per their own needs, which is given to themselves and Use by a person authorized by you Define the class library. In the program development work, the class library is extremely useful; it can decrease the user’s own access to classes and member functions. The workload characterized by the line.
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 gave by the C++ system in the program. For instance, the user is calling the sin function, you just need to include the header file that contains the declaration of this function into the program to call the library function without seeing how the sin function is executed (how the function value is determined). 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 a successful method for users to use the class library. Public interface, users can use related classes just through header files. This header text is visible and accessible to users, any user who wants to use this class just needs to include this header file.
The separation of interface and implementation creates great conditions for software developers to furnish users with class libraries. The developer put the declarations of the various classes needed by the user in various 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 characterized by the member function. Software vendors furnish users with the implementation of these header files and classes the target code (the source code of the function definition is not given). At the point when users use the classes in the class library, they just need to add the applicable header files Included in your own program; you can interface the object code characterized by the member function after compilation. Users can see the Header file Declaration and the prototype declaration of the member function, yet the source code of the definition of the member function can’t be seen, not to mention the change of the definition of member function protects the rights and interests of developers. Because of the rise of class libraries, users can easily use the general or specialized amassed practically speaking like using parts. The class used extraordinarily reduces the workload of program design and viably improves work proficiency.
Several terms in object-oriented programming
Anyhow, I will present a couple of terms in object-oriented programming: The member functions of the class reflect the behavior of the object. It is called “method” in object program hypothesis. “Method” refers to the control of data. A “method” corresponds to an operation. Obviously, just methods (member functions) that are declared as open can be initiated by the outside world of the object. Outside is Enact the important method by sending a “message”. The so-called “message” is really a command, a Sentence to accomplish. front stud.display(); It is a “message” sent to the object stud to inform the object stud to execute the display “method” (i.e. 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 numerous new terms. Readers are advised not to be scared or stumped by it. Truth be told, from pragmatic applications, The perspective is not convoluted. The requirements and methods of studying applied courses and studying theoratical courses are extraordinary. To average for non-professional readers who are new to C++, they just need to have an overall understanding of object-oriented concepts. The focus of learning it should be set on mastering the genuine application, especially not to fall into the “large sea” of abstract terms toward the starting don’t bite the dust linguistic details regardless of essential and secondary. To be additionally studied and used later on, Will normally goes further to master.
Amazon Purchase Links:
*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!