0
0
C++programming~30 mins

Data hiding in C++ - Mini Project: Build & Apply

Choose your learning style9 modes available
Data Hiding in C++
πŸ“– Scenario: Imagine you are creating a simple bank account system. You want to keep the account balance safe so that it cannot be changed directly from outside the account. This is called data hiding.
🎯 Goal: You will create a class called BankAccount that hides the balance inside it. You will add a way to check the balance safely and a way to add money to the account.
πŸ“‹ What You'll Learn
Create a class called BankAccount with a private variable balance of type double.
Add a public method getBalance() that returns the current balance.
Add a public method deposit(double amount) that adds money to the balance.
Use data hiding to prevent direct access to balance from outside the class.
πŸ’‘ Why This Matters
🌍 Real World
Data hiding is used in real bank systems to protect account balances from accidental or unauthorized changes.
πŸ’Ό Career
Understanding data hiding is important for writing secure and reliable code in software development jobs.
Progress0 / 4 steps
1
Create the BankAccount class with a private balance
Create a class called BankAccount with a private variable balance of type double initialized to 0.0.
C++
Need a hint?

Use the private: keyword to hide the balance variable inside the class.

2
Add a public method to get the balance
Add a public method called getBalance() that returns the value of balance. Use public: to make the method accessible outside the class.
C++
Need a hint?

The getBalance() method should return the private balance variable.

3
Add a public method to deposit money
Add a public method called deposit that takes a double amount parameter and adds it to balance.
C++
Need a hint?

The deposit method should add the amount to the private balance.

4
Create an object and test the methods
Create an object called myAccount of class BankAccount. Use deposit(100.0) to add money and then print the balance using getBalance().
C++
Need a hint?

Use std::cout to print the balance returned by getBalance().