C++ Data Encapsulation

Data Encapsulation is a fundamental concept of object-oriented programming (OOP), which is implemented by encapsulating data and the functions that operate on the data within a class. This encapsulation ensures the privacy and integrity of the data, preventing external code from directly accessing and modifying it.

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

  • Program statements (code):These are the parts of the program that perform actions; they are called functions.
  • Program data:Data is the information of the program, which is affected by the program's functions.

Encapsulation is a concept in object-oriented programming that binds together data and the functions that operate on the data, thereby avoiding interference and misuse from the outside world, thus ensuring safety. Data encapsulation leads to another important OOP concept, namelyData Hiding。

Data Encapsulationis a mechanism that binds data and the functions that operate on the data together,Data Abstractionis a mechanism that exposes only the interface to users while hiding the specific implementation details.

C++ through creatingClassto support encapsulation and data hiding (public, protected, private). We already know that classes contain private members, protected members, and public members. By default, all items defined in a class are private. For example:

class Box { public: double getVolume(void) { return length * breadth * height; } private: double length; // Length double breadth; // Width double height; // Height };

The variables length, breadth, and height are all private. This means they can only be accessed by other members in the Box class, not by other parts of the program. This is a way to achieve encapsulation.

To make members of a class public (that is, accessible to other parts of the program), thepublickeyword must be used before these members. 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 will expose implementation details, thereby reducing encapsulation. The ideal approach is to hide the implementation details of each class as much as possible.

Access modifiers:

  • private: Private members can only be accessed within the class, and cannot be directly accessed by code outside the class.
  • public: Public members can be directly accessed by code outside the class.
  • protected: Protected members can be accessed by the class and its derived classes.

Example of data encapsulation

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

Example

#include <iostream> using namespace std; class Adder{ public: // constructor Adder(int i = 0) { total = i; } // External interface void addNum(int number) { total += number; } // External interface int getTotal() { return total; }; private: // Data hidden from the outside 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 numbers and returns the sum. Public membersaddNumandgetTotalare the external interface; users need to know them in order to use the class. Private memberstotalare hidden from the outside; users do not need to know about them, but they are necessary for the class to work properly.

Data encapsulation is implemented through classes and access modifiers (public, private, protected). Here is a simple example:

Example

#include <iostream>
using namespace std;

class Student {
private:
    string name;
    int age;

public:
    // constructor
    Student(string studentName, int studentAge) {
        name = studentName;
        age = studentAge;
    }

    // Accessor function (getter)
    string getName() {
        return name;
    }

    int getAge() {
        return age;
    }

    // Modifier function (setter)
    void setName(string studentName) {
        name = studentName;
    }

    void setAge(int studentAge) {
        if (studentAge > 0) {
            age = studentAge;
        } else {
            cout << "Invalid age!" << endl;
        }
    }

    // Print student information
    void printInfo() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

int main() {
    // Create a Student object
    Student student1("Alice", 20);

    // Access and modify data
    student1.printInfo();

    student1.setName("Bob");
    student1.setAge(22);

    student1.printInfo();

    return 0;
}

Design Strategy

Normally, we set class member states to private unless we really need to expose them, in order to ensure goodEncapsulation。

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

Advantages of data encapsulation

  • Data Hiding: By declaring data members as private, external code is prevented from directly accessing these data.
  • Improve code maintainability: Provide public methods to access and modify data, which allows the internal implementation of the class to be modified without affecting external code.
  • Enhance security: Prevent illegal data input and improper modification operations.
  • Implement abstraction: Provide a mechanism such that users do not need to understand the internal implementation details of the class; they only need to know how to use the class's public interface.
other extensions