- Examples
Here are a few examples of the different types of methods that we explored in the previous lesson.
We'll cover the following...
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 by1
. -
On lines 22 and 29, we can see that the static
getDeposits()
method can be called without an instance ofAccount
. -
After the creation of
account1
andaccount2
, the value ofdeposits
is incremented to2
. We ...