A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/cpp/encapsulation-in-cpp/ below:

Encapsulation in C++ - GeeksforGeeks

Encapsulation in C++

Last Updated : 07 Aug, 2025

Encapsulation means combining data and the functions that work on that data into a single unit, like a class. In Object-Oriented Programming, it helps keep things organized and secure.

For example, think of a company with different departments—finance, sales, and accounts. Each department handles its own tasks and data. The finance department deals only with financial records, and the sales department handles only sales. Just like that, in programming, each class manages its own data and operations, keeping everything separate and protected. That's encapsulation.

In C++, OOPs encapsulation is implemented using classes and access specifiers that keeps the data, and the manipulating methods enclosed inside a single unit. The direct advantage of this packaging is that only the required components are visible to the user, and other information is hidden.

Example

C++
class Person {
public:
    
    // Data/information
    int socialID;
    string name;

    // Functions that work in this data
    Person(string n, int id) {}
    bool validateID() {}
};

In the above, encapsulation is demonstrated through the Person class, which encapsulates both data and the methods that represents the details of a real-world person.

Encapsulation facilitates data hiding in C++ by using private, protected and public access specifiers for restricting access to the class member functions and data members. For example, the above class Person can be rewritten as:

C++
class Person {
    
    // Data/information not accessible outside
    int socialID;
    string name;
    
public:

    // Functions that work in this data
    Person(string n, int id) {}
    bool validateID() {}
};

The class has two private data members: socialID and name. The private access specifier ensures that the socialID and name cannot be accessed directly from outside the class, enforcing data hiding. But there may be cases where you need to access or modify the private members such as name. This can be done by using getter and setter methods:

C++
#include <iostream>
#include <string>
using namespace std;

// Class that represents a person
class Person {

    // private members that will be hidden
    int socialID;
    string name;

public:
    // Constructor using initialization list
    Person(string n, int id) : name(n), socialID(id) {}

    // Getter for name (const as it doesn't modify the object)
    string getName() const {
        return name;
    }

    // Optional setter for name
    void setName(string newName) {
        name = newName;
    }

    // Validates the socialID
    bool validateID() const {
        return (socialID >= 0 && socialID <= 1001);
    }
};

int main() {
    Person p1("Geek", 503);

    if (!p1.validateID())
        cout << "Invalid SocialID\n";

    cout << "Name: " << p1.getName() << endl;

    return 0;
}

Public method getName() provide controlled access to the name data. Similar function to modify the name can also be created.

Note: The general encapsulation can be implemented using techniques other than classes but in OOPs language, it is implemented using classes.

Advantages and Disadvantages of Encapsulation:

Advantages of Encapsulation:

  1. Data Hiding:
    Internal object details are hidden from the outside world using access modifiers (like private), preventing unauthorized access.
  2. Improved Maintainability:
    Changes to internal code can be made with minimal impact on external code that uses the class, as long as the interface (public methods) remains the same.
  3. Reusability:
    Encapsulated code is modular and self-contained, making it easy to reuse in other parts of a program or in different projects.
  4. Improved Code Organization:
    Related variables and functions are grouped logically inside the same class, improving readability and structure.
  5. Flexibility and Control:
    By exposing only specific methods, the developer controls how data is accessed or modified. You can add validation or logic inside setters to ensure proper usage.
  6. Better Testing and Debugging:
    Encapsulated classes are easier to test individually (unit testing), and bugs are easier to isolate.
Disadvantages of Encapsulation:
  1. Increased Code Complexity:
    Writing getters and setters for every variable might feel repetitive and increase code size, especially in simple programs.
  2. Performance Overhead:
    Using methods instead of direct variable access can introduce slight overhead in performance-critical applications.
  3. Overuse of Accessors Can Break Encapsulation:
    If all fields have public getters and setters without restrictions, then the benefits of encapsulation are lost—it becomes just data exposure in disguise.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4