I am trying to learn some c++. To do this I have chosen to write an emulator. I had it up and running, but decided to try to make a better architecture. I have a strange problem that I don't understand. If I compile the following code (Visual C++ 2000 Express Edition) I get an error message: "Unhandled exception at 0x0041183f in test.exe: 0xC0000005: Access violation reading location 0x00000004."
If I cut the code from cpu.cpp and paste in main.cpp it is working. Can somebody try to explain to me what is the problem with my code/design?
main.h
typedef unsigned char u8;
typedef unsigned short u16;
// Forward declare the required classes
class Cpu;
class Memory;
class Gameboy
{
public:
Cpu *cpu;
Memory *memory;
Gameboy();
~Gameboy();
void Start();
};
static Gameboy *gb;
class Memory
{
public:
u8 read(u16 addr) const;
void write(u16 addr, u8 value);
private:
u8 _memory[0xffff];
};
class Cpu {
public:
void Run();
};
main.cpp
#include <iostream>
#include "main.h"
int main(int argc, char *argv[])
{
gb = new Gameboy();
gb->Start();
system("PAUSE");
return 0;
}
u8 Memory::read(u16 addr) const { return _memory[addr];}
void Memory::write(u16 addr, u8 value) { _memory[addr] = value; }
Gameboy::Gameboy() { this->cpu = new Cpu(); this->memory = new Memory(); }
Gameboy::~Gameboy() { delete cpu; delete memory; }
void Gameboy::Start() { cpu->Run(); }
cpu.cpp
#include <iostream>
#include "main.h"
void Cpu::Run() {
gb->memory->write(0xff40, 0x10);
printf("[Debug] 0xff40: %.2X\n", gb->memory->read(0xff40));
}