0
0
C++programming~5 mins

Why encapsulation is required in C++

Choose your learning style9 modes available
Introduction

Encapsulation helps keep data safe and hides details inside a class. It makes programs easier to understand and change.

When you want to protect important data from being changed directly.
When you want to hide complex details and show only simple actions.
When you want to control how data is accessed or updated.
When you want to make your code easier to fix or improve later.
When you want to group related data and functions together.
Syntax
C++
class ClassName {
private:
    // private data members
public:
    // public functions to access data
};
Use private to hide data inside the class.
Use public functions to allow safe access to the data.
Examples
This class hides the balance and only allows setting it if the amount is not negative.
C++
class BankAccount {
private:
    double balance;
public:
    void setBalance(double amount) {
        if (amount >= 0) balance = amount;
    }
    double getBalance() {
        return balance;
    }
};
The speed is hidden and can only be changed safely through setSpeed.
C++
class Car {
private:
    int speed;
public:
    void setSpeed(int s) {
        if (s >= 0) speed = s;
    }
    int getSpeed() {
        return speed;
    }
};
Sample Program

This program shows how encapsulation protects the age value. It only allows valid ages to be set.

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

class Person {
private:
    int age;
public:
    void setAge(int a) {
        if (a >= 0 && a <= 120) {
            age = a;
        } else {
            cout << "Invalid age" << endl;
        }
    }
    int getAge() {
        return age;
    }
};

int main() {
    Person p;
    p.setAge(25);
    cout << "Age: " << p.getAge() << endl;
    p.setAge(-5); // invalid
    cout << "Age after invalid set: " << p.getAge() << endl;
    return 0;
}
OutputSuccess
Important Notes

Encapsulation helps avoid mistakes by controlling how data changes.

It also makes your code easier to fix if something goes wrong.

Summary

Encapsulation hides data to protect it.

It uses private data and public functions.

This makes code safer and easier to manage.