Challenge: Access Modifiers
Swipe to start coding
Imagine you are creating a digital wallet application. You need to create a DigitalWallet class that represents a userβs wallet where they can store money.
-
Define access modifiers for the class fields:
balanceshould be private to prevent direct modification from outside the class.ownershould be protected to allow access in potential subclasses.- Methods like
addMoneyandshowBalanceshould be public so that external code can safely interact with the wallet.
-
Implement a constructor using the initializer list syntax:
- It should take
ownerNameas a parameter. - Initialize
ownerwith the passedownerName. - Initialize
balanceto0.0.
- It should take
-
Implement the
addMoneymethod:- Check if the amount is greater than 0.
- If yes, add it to
balanceand print a message like"150$ added to Alice's wallet." - Otherwise, print
"Invalid amount!".
-
Implement the
showBalancemethod:- Print the ownerβs name and the current balance in a readable format.
Solution
solution.cpp
Thanks for your feedback!
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Awesome!
Completion rate improved to 3.13
Challenge: Access Modifiers
Swipe to show menu
Swipe to start coding
Imagine you are creating a digital wallet application. You need to create a DigitalWallet class that represents a userβs wallet where they can store money.
-
Define access modifiers for the class fields:
balanceshould be private to prevent direct modification from outside the class.ownershould be protected to allow access in potential subclasses.- Methods like
addMoneyandshowBalanceshould be public so that external code can safely interact with the wallet.
-
Implement a constructor using the initializer list syntax:
- It should take
ownerNameas a parameter. - Initialize
ownerwith the passedownerName. - Initialize
balanceto0.0.
- It should take
-
Implement the
addMoneymethod:- Check if the amount is greater than 0.
- If yes, add it to
balanceand print a message like"150$ added to Alice's wallet." - Otherwise, print
"Invalid amount!".
-
Implement the
showBalancemethod:- Print the ownerβs name and the current balance in a readable format.
Solution
solution.cpp
Thanks for your feedback!
single