C++: Static variable

Let’s consider the interest rate of a bank.  If the interest rate of a bank is updated today, all calculations should use the new value immediately.

In an OOP, this can be done by declaring a static variable of a class.  If the value of this static variable is updated, all values of its related instances will be updated to the new value.

So, in a way, there is only one interestRate object that will be shared by all the Account objects.

To access the static variable, we use the scope operator :: as shown in the example below.  A static variable can only be assessed by a static function.

#include <cstdlib>
#include <iostream>

using namespace std;

class Account {

    static double rate() {
        return interestRate;
    static double interestRate;

double Account::interestRate = 12;

int main(int argc, char** argv) {
    cout << Account::rate();

    return 0;


Series Navigation<< C++: Inheritance and virtual method
C++: An experiment on a static variable >>