Home Tutorials C++ Tutorial Access Specifiers and Encapsulation
Access Specifiers and Encapsulation

Access Specifiers and Encapsulation


Access Specifiers and Encapsulation

Definition: Encapsulation is the process of bundling data (variables) and the methods that operate on that data into a single unit called a class. To protect this data, C++ uses Access Specifiers to define how the members (attributes and methods) of a class can be accessed from outside the class.

Why: Encapsulation is a fundamental pillar of Object-Oriented Programming. It follows the principle of "Data Hiding," which ensures that sensitive information is hidden from the outside world and can only be modified through specific public functions. This prevents accidental corruption of data and makes the code more secure and easier to maintain.


The Three Access Specifiers

In C++, there are three keywords used to control access to class members:

Specifier Description
public Members are accessible from outside the class.
private Members cannot be accessed (or viewed) from outside the class. This is the default for C++ classes.
protected Members cannot be accessed from outside the class, however, they can be accessed in inherited classes (child classes).

Example: Encapsulation using Getters and Setters

In this example, the salary variable is private, making it inaccessible to the main() function directly. Instead, we use "Getter" and "Setter" methods to interact with the data safely:

#include <iostream>
using namespace std;

class Employee {
  private:
    int salary; // Restricted access

  public:
    // Setter: Allows controlled modification
    void setSalary(int s) {
        salary = s;
    }
    // Getter: Allows controlled viewing
    int getSalary() {
        return salary;
    }
};

int main() {
    Employee e1;
    
    // e1.salary = 30000; // This would cause a Compiler Error!
    
    e1.setSalary(30000); // Accessing via public method
    cout << "Salary: " << e1.getSalary() << endl;
    
    return 0;
}

Key Notes

  • Why use Getters/Setters? They allow you to add validation logic. For example, in setSalary(), you could add an if statement to ensure the salary is never a negative number.
  • Security: By making attributes private, you control exactly how your data is used, reducing the risk of bugs caused by external code changing values unexpectedly.
  • Default Behavior: If you forget to add an access specifier in a C++ class, all members are private by default. In a struct, they are public by default.
  • Best Practice: It is a standard professional practice to keep all class variables (attributes) private and provide public methods to interact with them only if necessary.

🏋️ Test Yourself With Exercises

Take our quiz on Access Specifiers and Encapsulation to test your knowledge.

Browse Quizzes »