๐ Scenario: You are creating a simple program to manage a bank account. You want to keep the account balance safe and only allow changes through specific actions like deposits and withdrawals.
๐ฏ Goal: Build a C++ class called BankAccount that uses encapsulation to protect the account balance. You will create private data, public methods to interact with it, and show how to use the class safely.
๐ What You'll Learn
Create a class BankAccount with a private variable balance of type double.
Add a public constructor that sets the initial balance.
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.
Create an object of BankAccount and demonstrate deposits, withdrawals, and balance checks.
๐ก Why This Matters
๐ Real World
Encapsulation is used in real banking software to protect account data and ensure only valid operations change balances.
๐ผ Career
Understanding encapsulation is essential for software developers to write secure and maintainable code, especially in finance and data-sensitive applications.
Progress0 / 4 steps
1
Create the BankAccount class with private balance
Create a class called BankAccount with a private variable balance of type double. Do not add any methods yet.
C++
Hint
Use the private: keyword to hide the balance variable inside the class.
2
Add constructor to set initial balance
Add a public constructor to BankAccount that takes a double parameter called initialBalance and sets the private balance variable to this value.
C++
Hint
Use the constructor to set the private balance when creating an object.
3
Add deposit and withdraw methods
Add two public methods to BankAccount: deposit that takes a double amount and adds it to balance, and withdraw that takes a double amount and subtracts it from balance only if balance is enough.
C++
Hint
Use if to check if there is enough balance before withdrawing.
4
Add getBalance method and test the class
Add a public method getBalance that returns the current balance. Then create a BankAccount object called myAccount with initial balance 100.0. Deposit 50.0, withdraw 30.0, and print the final balance using getBalance.
C++
Hint
Return the balance in getBalance. Use std::cout to print the balance in main.
Practice
(1/5)
1. What is the main purpose of encapsulation in C++?
easy
A. To make the program run faster
B. To hide data and protect it from unauthorized access
C. To allow direct access to all class members
D. To increase the size of the program
Solution
Step 1: Understand encapsulation concept
Encapsulation means hiding the internal details of a class to protect data.
Step 2: Identify the main goal
The goal is to prevent wrong or unauthorized changes by restricting direct access.
Final Answer:
To hide data and protect it from unauthorized access -> Option B
Quick Check:
Encapsulation = Data protection [OK]
Hint: Encapsulation means hiding data safely [OK]
Common Mistakes:
Thinking encapsulation speeds up code
Believing all data should be public
Confusing encapsulation with inheritance
2. Which of the following is the correct way to declare a private data member in a C++ class?
easy
A. private: int age;
B. int age; // private by default
C. protected int age;
D. public int age;
Solution
Step 1: Recall C++ access specifiers
Private members must be declared after the keyword 'private:' in a class.
Step 2: Check each option
private: int age; uses 'private:' correctly before 'int age;'. Others are either public, protected, or missing specifier.
Final Answer:
private: int age; -> Option A
Quick Check:
Private members use 'private:' label [OK]
Hint: Use 'private:' label before private members [OK]
Common Mistakes:
Assuming members are private by default
Using 'private' without colon
Declaring private members as public
3. What will be the output of this C++ code?
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;
}
medium
A. 0
B. Compilation error
C. 10
D. Garbage value
Solution
Step 1: Understand class methods
The method setLength sets the private member length to 10.
Step 2: Check output statement
getLength returns length, which was set to 10, so output is 10.
Final Answer:
10 -> Option C
Quick Check:
Setter sets 10, getter returns 10 [OK]
Hint: Setter sets value, getter returns it [OK]
Common Mistakes:
Expecting default 0 without setting
Thinking private members can't be accessed via methods
Confusing compilation error due to private member
4. Identify the error in this C++ class related to encapsulation:
class Person {
public:
int age;
void setAge(int a) { age = a; }
int getAge() { return age; }
};
int main() {
Person p;
p.age = -5;
std::cout << p.getAge();
return 0;
}
medium
A. Age should be private to prevent invalid values
B. setAge method is missing return type
C. getAge should be private
D. No error, code is correct
Solution
Step 1: Check data member access
Age is public, so it can be set directly to invalid value -5.
Step 2: Understand encapsulation best practice
Age should be private and setAge should validate input to prevent invalid values.
Final Answer:
Age should be private to prevent invalid values -> Option A
Quick Check:
Private data prevents invalid direct changes [OK]
Hint: Make data private to control changes [OK]
Common Mistakes:
Thinking public data is safe
Believing getters should be private
Ignoring validation in setters
5. You want to protect a class's data member balance so it cannot be set to a negative value. Which is the best encapsulation practice to achieve this?
hard
A. Make balance public and check value outside the class
B. Make balance protected and allow derived classes to set it freely
C. Remove balance and use a global variable instead
D. Make balance private and provide a setter that validates input
Solution
Step 1: Understand data protection need
To prevent negative values, direct access must be blocked.
Step 2: Use private data with validation
Making balance private and using a setter method to check values ensures safety.
Final Answer:
Make balance private and provide a setter that validates input -> Option D
Quick Check:
Private data + validated setter = safe encapsulation [OK]
Hint: Use private data and validate in setter [OK]
Common Mistakes:
Leaving data public for easy access
Using protected without validation
Using global variables for encapsulation
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.