C++: An experiment on a static variable

Here, we create an Account class and create several instances of the class.  On each call to the constructor, the static variable is incremented.

Though we have a few instances of the same object, as we have defined the variable as static, we are actually incrementing the same variable.

#include <cstdlib>
#include <iostream>

using namespace std;

class Account {

    static int interestRate;

    static int rate() {

        return interestRate;


    Account(int yr) {
        year = yr;
        cout << interestRate++ << endl;
        cout << interestRate++ << endl;
        cout << "Constructor called" << endl;


    int year;


int Account::interestRate = 10;

int main(int argc, char** argv) {

    Account A1(12);
    Account A2(12);
    Account A3(12);
    cout << Account::rate() << endl;
    cout << Account::rate() << endl;   
    cout << Account::rate() << endl;

    return 0;


Series Navigation<< C++: Static variable
C++: Members of a subclass >>