Hi everyone,

I writing a program in which two methods I want to count when it is called. I don't know how to do this.

//parent class
void BankAccount::deposit(double dep)
    if(dep > 0)
        balance += dep;

void BankAccount::withdraw(double wd)
    if(wd > 0 && wd <= balance)
        balance -= wd;

That is transactionCount is a variable which is incremented when anyone of the above function is called.

//child class

    transactionCount = 0;


You've pretty much described the use case for static data members:

#include <iostream>

class BankAccount {
    void Credit(double amount)
        std::cout<<"Crediting "<< amount <<'\n';

    void Debit(double amount)
        std::cout<<"Debiting "<< amount <<'\n';

    int Transactions() const { return transactions; }
    static int transactions;

int BankAccount::transactions = 0;

int main(void)
    BankAccount acct;

    std::cout<<"Transactions: "<< acct.Transactions() <<'\n';
    std::cout<<"Transactions: "<< acct.Transactions() <<'\n';
I like this answer.

use case for static data members

If there is only ever a single BankAccount or the op wants a count across all accounts I would agree. However, if you did that with something like

BankAccount mary; 
CheckingAccount jane;

I think Jane would be surprised to hear about that activity on her account.

You could get the same behavior (with the exception of counts across all accounts) if you just used a private variable and dropped the static.

This article has been dead for over six months. Start a new discussion instead.