- Examples

Here are a few examples of the different types of methods that we explored in the previous lesson.

Static methods #

Press + to interact
#include <iostream>
class Account{
public:
Account(){
++deposits;
}
static int getDeposits(){
return Account::deposits;
}
private:
static int deposits;
};
int Account::deposits= 0;
int main(){
std::cout << std::endl;
std::cout << "Account::getDeposits(): " << Account::getDeposits() << std::endl;
Account account1;
Account account2;
std::cout << "account1.getDeposits(): " << account2.getDeposits() << std::endl;
std::cout << "account2.getDeposits(): " << account1.getDeposits() << std::endl;
std::cout << "Account::getDeposits(): " << Account::getDeposits() << std::endl;
std::cout << std::endl;
}

Explanation #

  • The static attribute, deposits, is being initialized on line 8. Whenever the constructor is called, its value is incremented by 1.

  • On lines 22 and 29, we can see that the static getDeposits() method can be called without an instance of Account.

  • After the creation of account1 and account2, the value of deposits is incremented to 2. We ...