c sharp Logo

Encapsulation


Encapsulation in C++ is a programming technique that allows you to group related data and functions together into a single unit. This unit is called a class. Encapsulation helps to protect the data from unauthorized access and modification. It also makes the code more reusable and maintainable.

To encapsulate data in C++, you use the private access specifier. This tells the compiler that the data can only be accessed from within the class itself. To access the data from outside the class, you must provide public methods.

For example, the following code shows a simple class named Person that encapsulates the data of a person:

class Person {

private:

  std::string name;

  int age;

 

public:

  Person(std::string name, int age) : name(name), age(age) {}

 

  std::string

 GetName()

 const

 {

    return name;

  }

 

  int

 GetAge()

 const

 {

    return age;

  }

};

 

The name and age data members of the Person class are private. This means that they can only be accessed from within the Person class itself. To access the data from outside the class, you must use the public GetName() and GetAge() methods.

Benefits of using encapsulation

There are several benefits to using encapsulation in C++, including:

  • Data protection: Encapsulation helps to protect the data from unauthorized access and modification.
  • Code reuse: Encapsulation makes the code more reusable by grouping related data and functions together.
  • Code maintainability: Encapsulation makes the code more maintainable by making it easier to find and change related data and functions.

Example

The following code shows how to use the Person class to create a new Person object and access the data from outside the class:

Person person("John Doe", 30);

 

std::string name = person.GetName();

int age = person.GetAge();

 

std::cout << "Name: " << name << std::endl;

std::cout << "Age: " << age << std::endl;

 

Output:

Name: John Doe

Age: 30

 

Conclusion

Encapsulation is a powerful feature of C++ that can be used to write more robust, secure, and maintainable code. By understanding how to use encapsulation, you can write better C++ code.