All C++ programs have the following two basic elements:
- Program Statements (Code): This is the part of the program that performs actions, they are called functions.
- Program data: Data is program information that is affected by program functions.
Encapsulation is a concept of binding data and operational data functions in object-oriented programming to avoid interference and misuse by the outside world, thus ensuring security. Data encapsulation has led to another important OOP concept, data hiding.
Data Encapsulation is a mechanism for bundling data and operational data functions. Data Abstraction is a specific implementation that exposes the interface only to the user. The mechanism of hiding details.
C++ supports encapsulation and data hiding (public, protected, private) by creating classes. We already know that classes contain private (private), protected (protected), and public (public) members. By default, all items defined in a class are private. For example:
The variables length, breadth, and height are private. This means that they can only be accessed by other members of the Box class and not by other parts of the program. This is one way to implement encapsulation.
In order for members of a class to become public (that is, other parts of the program can also be accessed), they must be declared before the members using the public keyword. All variables or functions defined after the public identifier can be accessed by all other functions in the program.
Defining a class as a friend class of another class exposes implementation details and reduces encapsulation. The ideal approach is to hide the implementation details of each class as much as possible.
Example of data encapsulation
In a C++ program, any class with both public and private members can be used as an Example of data encapsulation and data abstraction. Please see the example below:
When the above code is compiled and executed, it produces the following results:
The above class adds the numbers and returns the sum. Public members addNum and getTotal are external interfaces that users need to know to use classes. The private member total is hidden from the outside, and the user does not need to know about it, but it is necessary for the class to work properly.
Usually, we will set the class member state to private (private) unless we really need to expose it to ensure good encapsulation.
This is usually applied to data members, but it also applies to all members, including virtual functions.