0

I am new to C++ and I am trying to start a project where every time I create a new instance of the ATM class it incements accountID by 1 and displays the current account ID. This is my code:

// Bank ATM.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include "ATM.h"


int main()
{
    ATM abunch[15];
    for (int i = 0; i < 15; i++){
        abunch[i] = ATM();
    }
    return 0;
}


//ATM.h
 #include "stdafx.h"
 #ifndef atm
#define atm
class ATM {
    static int accountID;

public:
    ATM();
};
int ATM::accountID = 0;
#endif


//ATM.cpp
#include "stdafx.h"
#include "ATM.h"
#include <iostream>
ATM::ATM() {
    ++accountID;
    std::cout << accountID;
}

I get The following error message: enter image description here

What am I doing wrong?

AndyG
  • 39,700
  • 8
  • 109
  • 143

1 Answers1

0

Because ATM::accountID is declared in a .h file, outside of a class, it is globally declared every time that file is included in another file. You include it twice; in main.cpp and in ATM.cpp. That's a no-no.

The declaration needs to move to ATM.cpp

//ATM.h
 #include "stdafx.h"
 #ifndef atm
#define atm
class ATM {
    static int accountID;

public:
    ATM();
};
int ATM::accountID = 0;   // <--- remove this line
#endif


//ATM.cpp
#include "stdafx.h"
#include "ATM.h"
#include <iostream>
int ATM::accountID = 0;   // <----put it here
ATM::ATM() {
    ++accountID;
    std::cout << accountID;
}
CAB
  • 1,106
  • 9
  • 23