Mark As Completed Discussion

Encapsulation

Encapsulation is one of the key principles of object-oriented programming (OOP) that focuses on hiding internal implementation details of a class and providing controlled access to the class's members. By encapsulating data and methods together, encapsulation helps create objects that are self-contained and modular.

In C++, encapsulation is achieved by using access specifiers to control the visibility of class members. The three access specifiers in C++ are:

  • public: Class members declared as public are accessible from any part of the program.
  • private: Class members declared as private are only accessible within the class itself.
  • protected: Class members declared as protected are accessible within the class and its derived classes.

By default, class members are private if no access specifier is specified.

Let's take a look at an example that demonstrates encapsulation in C++:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4// Encapsulated class
5
6class Player {
7private:
8    string name;
9    int age;
10
11public:
12    void setName(string playerName) {
13        name = playerName;
14    }
15
16    void setAge(int playerAge) {
17        age = playerAge;
18    }
19
20    string getName() {
21        return name;
22    }
23
24    int getAge() {
25        return age;
26    }
27};
28
29int main() {
30    Player player;
31    player.setName("John Doe");
32    player.setAge(25);
33
34    cout << "Player Name: " << player.getName() << endl;
35    cout << "Player Age: " << player.getAge() << endl;
36
37    return 0;
38}

In this example, we have a class called Player that encapsulates the name and age data members and provides public member functions to set and get their values. The setName and setAge functions are used to set the values of the private members, and the getName and getAge functions are used to retrieve their values.

By encapsulating the data members and providing controlled access through member functions, we ensure that the internal details of the Player class are hidden from outside code. The main function demonstrates how the encapsulated class can be used to create a Player object and access its data through the public member functions.

Encapsulation enhances the security, reliability, and maintainability of code by preventing direct access to internal data and providing a consistent interface for interacting with objects. It also allows for data validation and error checking within the encapsulated class, ensuring that the data remains in a valid state.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment