Introduction
Encapsulation helps keep data safe and hides details inside a class. It makes programs easier to understand and change.
Encapsulation helps keep data safe and hides details inside a class. It makes programs easier to understand and change.
class ClassName { private: // private data members public: // public functions to access data };
class BankAccount { private: double balance; public: void setBalance(double amount) { if (amount >= 0) balance = amount; } double getBalance() { return balance; } };
class Car { private: int speed; public: void setSpeed(int s) { if (s >= 0) speed = s; } int getSpeed() { return speed; } };
This program shows how encapsulation protects the age value. It only allows valid ages to be set.
#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; }
Encapsulation helps avoid mistakes by controlling how data changes.
It also makes your code easier to fix if something goes wrong.
Encapsulation hides data to protect it.
It uses private data and public functions.
This makes code safer and easier to manage.
#include <iostream>
class Box {
private:
int length;
public:
void setLength(int len) { length = len; }
int getLength() { return length; }
};
int main() {
Box b;
b.setLength(10);
std::cout << b.getLength();
return 0;
}
What is the output when this program runs?#include <iostream>
class Person {
private:
int age;
public:
void setAge(int a) { age = a; }
int getAge() { return age; }
};
int main() {
Person p;
p.age = 25;
std::cout << p.getAge();
return 0;
}Pass the test and this pattern moves unknown