C++ Encapsulation
Learn C++ Encapsulation with simple explanations, practical examples, coding exercises, MCQs and interview questions.
Theory
Understand the concept step by step
C++ Encapsulation
Encapsulation means wrapping data and methods together inside a class.
It also helps control access to data using:
- public
- private
- protected
Example
class Account {
private:
int balance;
public:
void setBalance(int amount) {
balance = amount;
}
int getBalance() {
return balance;
}
};
Encapsulation helps protect data from direct access.
Example
See how the concept works in real code
#include <iostream>
using namespace std;
class Account {
private:
int balance;
public:
void setBalance(int amount) {
balance = amount;
}
int getBalance() {
return balance;
}
};
int main() {
Account account;
account.setBalance(5000);
cout << account.getBalance();
return 0;
}Output
Expected output of the example
5000
Practice
Try writing the program yourself
🎯 Practice Task
Rewrite the example program yourself without copying it. Then modify the values and observe how the output changes.
MCQs
Test your understanding
Quick Quiz
Test what you learned
What is the main topic covered in "C++ Encapsulation"?
Interview Questions
Prepare for C++ interviews
1. What is C++ Encapsulation?+
Review the theory and example above to prepare a clear, practical answer for this question.
2. Why is C++ Encapsulation important in C++?+
Review the theory and example above to prepare a clear, practical answer for this question.
3. Give a practical example of C++ Encapsulation.+
Review the theory and example above to prepare a clear, practical answer for this question.
Chapter 20 of 33
Keep going — you're doing great! 🚀