Detailed analysis of C++ data encapsulation and data abstraction

  • 2020-10-07 18:47:27
  • OfStack

C++ data encapsulation

All C++ programs have the following two basic elements:

Program statements (code) : These are the parts of a program that perform actions. They are called functions. Program data: Data is program information that can be affected by program functions.

Encapsulation is a concept in object-oriented programming that binds the functions of data and manipulation data to one, so as to avoid interference and misuse by the outside world, thus ensuring security. Data encapsulation leads to another important OOP concept, data hiding.

Data encapsulation is a mechanism for binding data to functions that manipulate data, while data abstraction is a mechanism for exposing interfaces only to the user while hiding implementation details.

C++ supports encapsulation and data hiding by creating classes (public, protected, private). We already know that classes contain private members (private), protected members (protected), and public members (public). By default, all items defined in a class are private. Such as:


class Box
{
  public:
   double getVolume(void)
   {
     return length * breadth * height;
   }
  private:
   double length;   //  The length of the 
   double breadth;   //  The width of the 
   double height;   //  highly 
};

The variables length, breadth, and height are private (private). This means that they can only be accessed by other members of the Box class, not by other parts of the program. This is one way to implement encapsulation.

In order for members in a class to become public (that is, accessible to other parts of the program), they must be declared in front of them using the public keyword. All variables or functions defined after the public identifier can be accessed by all other functions in the program.

Defining one class as a friend of another exposes the implementation details, thereby reducing encapsulation. It is ideal to hide the implementation details of each class as much as possible.

An instance of data encapsulation

In C++ programs, any class with public and private members can serve as an instance of data encapsulation and data abstraction. See the following example:


#include <iostream>
using namespace std;
 
class Adder{
  public:
   //  The constructor 
   Adder(int i = 0)
   {
    total = i;
   }
   //  External interface 
   void addNum(int number)
   {
     total += number;
   }
   //  External interface 
   int getTotal()
   {
     return total;
   };
  private:
   //  Hidden data 
   int total;
};
int main( )
{
  Adder a;
  
  a.addNum(10);
  a.addNum(20);
  a.addNum(30);
 
  cout << "Total " << a.getTotal() <<endl;
  return 0;
}

When the above code is compiled and executed, it produces the following results:

[

Total 60

]

The above class adds the Numbers and returns the sum. The public members addNum and getTotal are external interfaces that the user needs to know about in order to use the class. The private member total is hidden from the outside world, and the user does not need to know about it, but it is necessary for the class to work.

The design strategy

In general, we set the class member state to private (private), unless we really need to expose it to ensure good encapsulation.

This usually applies to data members, but it also applies to all members, including virtual functions.

C++ Data abstraction

Data abstraction refers to providing only critical information to the outside world and hiding the implementation details behind it, that is, presenting only the necessary information without presenting the details.

Data abstraction is a programming (design) technique that relies on the separation of interface and implementation.

Let's take a real examples in real life, such as a TV set, you can open and close, switching channels, adjust volume, add external components (e.g., speakers, video recorders, DVD players), but you don't know its internal implementation details, that is to say, you don't know how it is through the cable received signal, how to convert the signal, and finally displayed on the screen.

Therefore, we can say that the TV separates its internal implementation from the external interface. You can control the TV directly through its external interface (such as power button, remote control, volume controller) without knowing its internal implementation principle.

Now, let's get back to the point. In terms of C++ programming, the C++ class provides the possibility for data abstraction. They provide the outside world with a large number of public methods for manipulating object data, that is, the outside world is not actually aware of the internal implementation of the class.

For example, your program can call the sort() function without knowing the algorithm used to sort the data in the function. In fact, the underlying implementation of function ordering varies depending on the version of the library, and function calls work as long as the interface remains the same.

In C++, we use classes to define our own abstract data types (ADT). You can use the cout object of class iostream to output data to standard output as follows:


#include <iostream>
using namespace std;
 
int main( )
{
  cout << "Hello C++" <<endl;
  return 0;
}

Here, you don't need to understand how cout displays text on the user's screen. All you need to know is the public interface, and the underlying implementation of cout is free to change.

Access tags enforce abstraction

In C++, we use the access tag to define the abstract interface of the class. A class can contain zero or more access tags:

Members defined with common tags have access to all parts of the program. A data abstract view of type 1 is defined by its public members. Members defined with private tags cannot access the code that USES the class. The private section hides implementation details from code that USES the type.

There is no limit to the frequency of access tags. Each access label specifies the level of access defined by the member that follows. The specified access level is valid until the next access tag is encountered or a closing parenthesis is encountered for the class body.

The benefits of data abstraction

Data abstraction has two important advantages:

Classes are protected internally from an unintentional user-level error that causes the object state to be compromised. Class implementations may change over time to respond to changing requirements or error reports that require user-level code not to change.

If you define data members only in private parts of a class, the author of the class is free to change the data. If the implementation changes, you only need to examine the code of the class to see what the impact of the change will be. If the data is public, any functions that directly access data members of the old representation may be affected.

An instance of data abstraction

In C++ programs, any class with public and private members can be an instance of a data abstraction. See the following example:


#include <iostream>
using namespace std;
 
class Adder{
  public:
   //  The constructor 
   Adder(int i = 0)
   {
    total = i;
   }
   //  External interface 
   void addNum(int number)
   {
     total += number;
   }
   //  External interface 
   int getTotal()
   {
     return total;
   };
  private:
   //  Hidden data 
   int total;
};
int main( )
{
  Adder a;
  
  a.addNum(10);
  a.addNum(20);
  a.addNum(30);
 
  cout << "Total " << a.getTotal() <<endl;
  return 0;
}

When the above code is compiled and executed, it produces the following results:

[

Total 60

]

The above class adds the Numbers and returns the sum. The public members addNum and getTotal are external interfaces that the user needs to know about in order to use the class. The private member total is something the user does not need to know about, but is necessary for the class to work properly.

The design strategy

Abstractions separate code into interfaces and implementations. So when you design components, you must keep the interface independent of the implementation, so that if you change the underlying implementation, the interface will remain the same.

In this case, no matter what program USES the interface, the interface will not be affected, and you just need to recompile the latest implementation.

Above is the detailed analysis of C++ data encapsulation and data abstraction details, more about C++ data encapsulation and data abstraction information please pay attention to this site other related articles!


Related articles: