Original Post
Im currently learning how to implement function pointers for my 2D game project. Im planning to use them to run AI for the game. The idea is to have a single class called TaskManager which has the collection of all the AI functions and a Object struct thats stores and run an AI function on under certain condition. The codes i have written so far for testing: AppMain.cpp Board.h and .cpp where the game is runned TaskMgr.h and .cpp where the tasks are assigned to units The code compiles fine but when i run it there is an access violation error that occurs at the line. void mf_RunAI() { (Mgr->*pt2member)(this); }; Please help me out with this as it is very important to the game. Thanks. P.S. Im sorry that i did not put the codes in a code tag because i don't know how to. If anyone can tell me how please do. Edit: Codes in source tag thanks to silothesuper :P [Edited by - Flying_Dagger on August 20, 2006 3:05:30 AM]
include <iostream>
#include "Board.h"
#include "TaskMgr.h"
using namespace std;
void main (void) {
Board * newBoard;
newBoard = new Board();
newBoard->test->mf_RunAI();
cout<<newBoard->test->haha;
}
class TaskMgr;
struct Unit {
int haha;
TaskMgr * Mgr;
void (TaskMgr::*pt2member)(Unit *);
void mf_RunAI() { (Mgr->*pt2member)(this); };
};
class Board
{
public:
Board(void);
~Board(void);
Unit * test;
TaskMgr * mTMgr;
};
Board::Board(void)
{
mTMgr = new TaskMgr();
test = new Unit;
mTMgr->SetUp(test);
}
Board::~Board(void)
{
}
struct Unit;
class TaskMgr
{
public:
TaskMgr(void);
~TaskMgr(void);
void SetUp(Unit *);
void Addition(Unit *);
void Subtraction(Unit *);
};
TaskMgr::TaskMgr(void)
{
}
TaskMgr::~TaskMgr(void)
{
}
void TaskMgr::SetUp(Unit * target) {
target->haha = 0;
target->Mgr = this;
target->pt2member = &TaskMgr::Addition;
}
void TaskMgr::Addition(Unit * target) {
target->haha++;
}
void TaskMgr::Subtraction(Unit * target) {
target->haha--;
}