Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

C++ Encapsulation

What is Encapsulation?

Encapsulation is the practice of bundling data and the methods that operate on it into a single unit (class), and restricting direct access to the internal state. External code interacts only through a controlled public interface.

Benefits:

  • Prevents accidental corruption of internal state
  • Allows validation logic in setters
  • Internal implementation can change without breaking external code
  • Improves maintainability and testability
Encapsulation with Getters and Setters
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;

class Employee {
private:
    string name;
    int    age;
    double salary;

public:
    Employee(string name, int age, double salary) {
        setName(name);
        setAge(age);
        setSalary(salary);
    }

    // Getters
    string getName()   const { return name; }
    int    getAge()    const { return age; }
    double getSalary() const { return salary; }

    // Setters with validation
    void setName(const string &n) {
        if (n.empty()) throw invalid_argument("Name cannot be empty");
        name = n;
    }

    void setAge(int a) {
        if (a < 18 || a > 65)
            throw invalid_argument("Age must be 18–65");
        age = a;
    }

    void setSalary(double s) {
        if (s < 0) throw invalid_argument("Salary cannot be negative");
        salary = s;
    }

    void giveRaise(double percent) {
        salary *= (1.0 + percent / 100.0);
    }

    void display() const {
        cout << name << " | Age: " << age
             << " | Salary: $" << salary << endl;
    }
};

int main() {
    Employee emp("Alice", 30, 60000);
    emp.display();

    emp.giveRaise(10);
    emp.display();  // salary is now $66000

    // emp.salary = -1;  // ERROR: private member

    try {
        emp.setAge(100);  // throws invalid_argument
    } catch (const invalid_argument &e) {
        cout << "Error: " << e.what() << endl;
    }

    return 0;
}

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.