<aside> đź’ˇ Key Concept
This week you will learn about object interactions, modelling real world items with classes and static and non-static functions.
Learning Objectives
First, let’s implement the wallet class’s header file Wallet.h
. The wallet class contains the following functions:
Wallet()
: the class constructor that takes 0 argumentinsertCurrency
: insert currency and amount into the walletremoveCurrency
: remove an indicated currency with the indicated amount.toStrong
: get the currencies and the respective amounts in the wallet#include <string>
#include <map>
class Wallet
{
public:
Wallet();
/** insert currency to the wallet */
void insertCurrency(std::string type, double amount);
/** remove currency to the wallet */
bool removeCurrency(std::string type, double amount);
/** check if the wallet contains this much currency or more */
bool containsCurrency(std::string type, double amount);
/** get the currencies and the respective amounts in the wallet */
std::string toString();
private:
std::map<std::string, double> currencies;
};
Next, let’s create the wallet cpp file Wallet.cpp
and its skeleton, i.e., minimal code that allows the file to compile. What I normally do is to copy the function declaration from the header file to the cpp file, then add class scope to each function (e.g. Wallet::
) and change the ;
to {}
. If the function declare a return type, return a minimal value with that type.
#include "Wallet.h"
Wallet::Wallet() {
}
/** insert currency to the wallet */
void Wallet::insertCurrency(std::string type, double amount)
{
}
/** remove currency to the wallet */
bool Wallet::removeCurrency(std::string type, double amount) {
return true;
}
/** check if the wallet contains this much currency or more */
bool Wallet::containsCurrency(std::string type, double amount)
{
return false;
}
std::string Wallet::toString()
{
return "s";
}
In MerkelMain.h
file, include the Wallet.h
and introduce a private Wallet
object.
//...
#include "Wallet.h"
class MerkelMain
{
private:
// ...
Wallet wallet;
};
Go to MerkelMain.cpp
, in the init
function, call the insertCurrency
function to insert some dummy currency.