0

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;



}
3
Contributors
2
Replies
4
Views
5 Years
Discussion Span
Last Post by L7Sqr
2

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';
}
Votes + Comments
I like this answer.
0

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.

Edited by L7Sqr

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.