• Status: Solved
• Priority: Medium
• Security: Public
• Views: 329

# Static ints and functions

Hey everyone, im just trying to do a C++ question out of my textbook, but i cant make it run..

Code:

#include <iostream>

using namespace std;

class BankAccount{

public:
BankAccount(double amount = 0.0);
void deposit(double amount);
void withdraw(double amount);
int getAccNum() const;
double getBalance() const;
void printDetails()const;
static int getNumberOfAccs();

private:
double balance;
int accNum;
static int numberOfAccs;

};

BankAccount::BankAccount(double amount)
{
balance = amount;
numberOfAccs = 0;
accNum  =  numberOfAccs  * 1000;
numberOfAccs++;
}

void BankAccount::deposit(double amount)
{
balance += amount;

}

void BankAccount::withdraw(double amount)
{
balance -= amount;

}

int BankAccount::getAccNum() const
{
return accNum;
}

double BankAccount::getBalance() const
{
return balance;
}

void BankAccount::printDetails() const
{
cout << "For account number" << getAccNum() << "Has a balance of " <<  getBalance() << endl;

}

int BankAccount::getNumberOfAccs()
{
return numberOfAccs;
}

int main()
{

BankAccount Test(2000);

return 0;
}

basically what I have to do is each time a bankaccount constructor is used, numberOfAcc is incrememnted by one, then the instance variable accNum can then be initialised from the static variable .
e.g. if account numbers have 4 digits
accNum  =  numberOfAccs  * 1000;

Now, i think i have to initialise the static variable by doing something like:

BankAccount::numberOfAccs = 0;

but that doesn't seem to work. Does anyone have any pointers please?

0
Helix
• 2
• 2
1 Solution

Commented:
Hi Helix,
> >BankAccount::numberOfAccs = 0;

It should be in your *.cpp file, and you need the type.
int BankAccount::numberOfAccs = 0;

David Maisonave :-)
Cheers!
0

Commented:
In your original code, you're missing the type (int) for your static variable declaration.

Make sure that this is declared in your *.cpp file, and not in the header.
0

Author Commented:
Aha, got it to run, but for some reason its not incrementing...
0

Author Commented:
Nm got it working, thanks! :D
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.