After many hours of searching I still haven't found a solution to the following problem. In my game I make use of an abstract factory which generates objects. I'm trying to pass a function made in this factory, which generates bullets, to enemy. For this I tried using a function pointer which points to factory->getBullet() and passing it with the constructor of enemy. It failed :)
#include "Factory.h"
int main()
{
Factory* f = new Factory();
f->getEnemy(&f->getBullet);
return 0;
}
Factory.h
#include "Enemy.h";
#include "Bullet.h";
class Factory {
public:
Factory();
virtual ~Factory();
Enemy* getEnemy(Bullet* (*getBulletPtr)(int));
Bullet* getBullet(int damage);
};
Factory.cpp
#include "Factory.h"
Factory::Factory() {}
Factory::~Factory() {}
Enemy* Factory::getEnemy(Bullet* (*getBulletPtr)(int))
{return new Enemy(getBulletPtr);}
Bullet* Factory::getBullet(int damage)
{return new Bullet(damage);}
Enemy.h
#include "Bullet.h"
class Enemy
{
private:
Bullet* (*getBullet)(int) = NULL;
public:
Enemy(Bullet* (*getBulletPtr)(int));
virtual ~Enemy();
};
Enemy.cpp
#include "Enemy.h"
Enemy::Enemy(Bullet* (*getBulletPtr)(int))
{
getBullet = getBulletPtr;
getBullet(10);
}
Enemy::~Enemy() {}
Bullet.h
#include <iostream>
using namespace std;
class Bullet {
public:
Bullet(int damage);
virtual ~Bullet();
};
Bullet.cpp
#include "Bullet.h"
Bullet::Bullet(int damage)
{
cout << "This is a bullet: Damage:"<< damage << endl;
}
Bullet::~Bullet()
{}
When I try to run this code I get the following error:
ISO C++ forbids taking the address of a bound member function to form a pointer to member function. Say '&Factory::getBullet' [-fpermissive]
When I change
f->getEnemy(&f->getBullet);
to
f->getEnemy(&Factory::getBullet);
I get the following error:
no matching function for call to 'Factory::getEnemy(Bullet* (Factory::*)(int))'
How can I pass factory->getBullet function to my enemies.
Any help would be appreciated!