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

CheckingAccount::CheckingAccount
{
    transactionCount = 0;



}

Recommended Answers

All 2 Replies

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

#include <iostream>

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

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

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

int BankAccount::transactions = 0;

int main(void)
{
    BankAccount acct;

    std::cout<<"Transactions: "<< acct.Transactions() <<'\n';
    acct.Credit(123.45);
    acct.Debit(23.23);
    acct.Debit(1.23);
    std::cout<<"Transactions: "<< acct.Transactions() <<'\n';
}
commented: I like this answer. +6

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;
mary.Credit(100.00);
mary.Debit(50.00);

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.