0
0
C++programming~30 mins

Why encapsulation is required in C++ - See It in Action

Choose your learning style9 modes available
Why Encapsulation is Required in C++
πŸ“– Scenario: Imagine you are building a simple bank account system. You want to keep the account balance safe so that no one can change it directly by mistake. This is where encapsulation helps.
🎯 Goal: You will create a class called BankAccount that keeps the balance private. You will add methods to deposit money, withdraw money, and check the balance safely.
πŸ“‹ What You'll Learn
Create a class BankAccount with a private variable balance of type double
Add a public method deposit that adds money to balance
Add a public method withdraw that subtracts money from balance only if there is enough money
Add a public method getBalance that returns the current balance
Demonstrate that balance cannot be accessed directly from outside the class
πŸ’‘ Why This Matters
🌍 Real World
Banks and many software systems use encapsulation to protect sensitive data like account balances or personal information.
πŸ’Ό Career
Understanding encapsulation is essential for writing safe and maintainable code in professional software development.
Progress0 / 4 steps
1
Create the BankAccount class with private balance
Create a class called BankAccount with a private variable balance of type double initialized to 0.0.
C++
Need a hint?

Use private: to keep balance hidden from outside the class.

2
Add public methods to deposit and withdraw money
Add public methods deposit and withdraw to the BankAccount class. deposit should add a double amount to balance. withdraw should subtract amount from balance only if balance is enough.
C++
Need a hint?

Use if to check if there is enough balance before withdrawing.

3
Add a method to get the current balance
Add a public method getBalance to the BankAccount class that returns the current balance as a double.
C++
Need a hint?

Return the private balance so outside code can see it safely.

4
Use the BankAccount class and show encapsulation
Create a BankAccount object called myAccount. Deposit 100.0, withdraw 30.0, then print the balance using getBalance(). Try to access balance directly (this should cause an error).
C++
Need a hint?

Use myAccount.deposit(100.0); and myAccount.withdraw(30.0); then print myAccount.getBalance().