Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Challenge: Access Modifiers | Encapsulation Overview
C++ OOP

bookChallenge: Access Modifiers

Task

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.

  1. Define access modifiers for the class fields:

    • balance should be private to prevent direct modification from outside the class.
    • owner should be protected to allow access in potential subclasses.
    • Methods like addMoney and showBalance should be public so that external code can safely interact with the wallet.
  2. Implement a constructor using the initializer list syntax:

    • It should take ownerName as a parameter.
    • Initialize owner with the passed ownerName.
    • Initialize balance to 0.0.
  3. Implement the addMoney method:

    • Check if the amount is greater than 0.
    • If yes, add it to balance and print a message like "150$ added to Alice's wallet."
    • Otherwise, print "Invalid amount!".
  4. Implement the showBalance method:

    • Print the owner’s name and the current balance in a readable format.

Solution

solution.cpp

solution.cpp

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 3. ChapterΒ 3
single

single

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

close

Awesome!

Completion rate improved to 3.13

bookChallenge: Access Modifiers

Swipe to show menu

Task

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.

  1. Define access modifiers for the class fields:

    • balance should be private to prevent direct modification from outside the class.
    • owner should be protected to allow access in potential subclasses.
    • Methods like addMoney and showBalance should be public so that external code can safely interact with the wallet.
  2. Implement a constructor using the initializer list syntax:

    • It should take ownerName as a parameter.
    • Initialize owner with the passed ownerName.
    • Initialize balance to 0.0.
  3. Implement the addMoney method:

    • Check if the amount is greater than 0.
    • If yes, add it to balance and print a message like "150$ added to Alice's wallet."
    • Otherwise, print "Invalid amount!".
  4. Implement the showBalance method:

    • Print the owner’s name and the current balance in a readable format.

Solution

solution.cpp

solution.cpp

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 3. ChapterΒ 3
single

single

some-alt