Encapsulation helps keep data safe and organized inside a class. It hides details so others use the class easily without breaking it.
0
0
Encapsulation best practices in C++
Introduction
When you want to protect important data from being changed directly.
When you want to control how data is accessed or updated.
When you want to make your code easier to understand and maintain.
When you want to hide complex details and show only simple actions.
When you want to prevent accidental mistakes by other parts of the program.
Syntax
C++
class ClassName { private: // private data members public: // public methods to access or modify data };
Use private to hide data inside the class.
Use public methods to allow safe access to the data.
Examples
This class hides the
balance and only lets you add money or check the balance safely.C++
class BankAccount { private: double balance; public: BankAccount() : balance(0) {} void deposit(double amount) { if (amount > 0) balance += amount; } double getBalance() const { return balance; } };
Here, the
name is private and can only be changed or read through methods.C++
class Person { private: std::string name; public: void setName(const std::string& newName) { name = newName; } std::string getName() const { return name; } };
Sample Program
This program shows a Car class that keeps model and speed private. You can only change speed using accelerate and brake methods, which keep speed safe and logical.
C++
#include <iostream> #include <string> class Car { private: std::string model; int speed; public: Car(const std::string& m) : model(m), speed(0) {} void accelerate(int amount) { if (amount > 0) speed += amount; } void brake(int amount) { if (amount > 0 && speed - amount >= 0) speed -= amount; } int getSpeed() const { return speed; } std::string getModel() const { return model; } }; int main() { Car myCar("Toyota"); myCar.accelerate(50); std::cout << myCar.getModel() << " speed: " << myCar.getSpeed() << " km/h\n"; myCar.brake(20); std::cout << myCar.getModel() << " speed after brake: " << myCar.getSpeed() << " km/h\n"; return 0; }
OutputSuccess
Important Notes
Always keep data members private unless you have a strong reason not to.
Use const methods when you do not change the object, to make your code safer.
Validate inputs inside methods to avoid invalid data changes.
Summary
Encapsulation hides data and protects it from wrong changes.
Use private data and public methods to control access.
Good encapsulation makes code easier to use and fix later.