Search⌘ K

- Examples

Explore static methods that operate without class instances, understand the this pointer for distinguishing object members, and learn how const and constexpr methods control data access and enable compile-time evaluation in C++ classes.

Static methods #

C++
#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 can check this by invoking getDeposits() ...