Reputation: 767
I have the following header:
class MyClass {
private:
static void (*OnRequest)();
static void (*OnReceive)(int numBytes);
public:
MyClass();
static void SetOnReceive(void (*function)(int));
static void SetOnRequest(void (*function)(void));
};
void NonClassFunction();
and the following declaration:
#include "MyClass.h"
MyClass::MyClass() {
...
}
void MyClass::SetOnReceive(void (*function)(int) ) {
OnReceive = function;
}
void MyClass::SetOnRequest( void (*function)(void) ) {
OnRequest = function;
}
void NonClassFunction() {
MyClass::OnRequest();
}
The code compiles fine but I get the following errors when I link:
unresolved symbol MyClass::OnReceive, first referenced in ./src/MyClass.obj
unresolved symbol MyClass::OnRequest, first referenced in ./src/MyClass.obj
I need OnRequest and OnReceive to function like a callback through NonClassFunction(). The NonClassFunction is being called by an interrupt so there is a bit of object oriented mangling going on here. MyClass is designed to be inherited. Ideally I would like OnRequest and OnReceive to be virtual but you cannot make static methods virtual.
Upvotes: 0
Views: 197
Reputation: 1014
i asked the same question recently how-to-send-a-message-to-the-class-that-created-the-object
enemies_array[0].enemy = new Enemy(this,&Game::EnemyEvent);
typedef void (Game::*ChangeFunc)(DWORD &)
Class Enemy
{
private:
ChangeFunc iChange;
Game *pGame;
}:
Enemy(Game *pCreatorGame, ChangeFunc iChangeHandler )
{
iChange = iChangeHandler;
pGame = pCreatorGame;
}
void Enemy::Draw(D3DGraphics& gfx)
{
(pGame->*iChange)(this->dwThreadID);
Upvotes: 0
Reputation: 208353
You provided the declarations of the function pointers, but not the definition. Add this to a single cpp file:
void (*MyClass::OnRequest)();
void (*MyClass::OnReceive)(int);
Upvotes: 1
Reputation: 63775
These two variables in your header:
static void (*OnRequest)();
static void (*OnReceive)(int numBytes);
Have not been defined.
Define them in your cpp file.
void (*MyClass::OnRequest)();
void (*MyClass::OnReceive)(int);
Upvotes: 1
Reputation: 361442
Those are linker error, which means the members are not defined. They're only declared.
The pointer members are static
members, so they need definition, which is outside the class.
Do this in the .cpp
file:
void (*MyClass::OnRequest)();
void (*MyClass::OnReceive)(int);
These are definitions, and what you've written in the class are only declarations.
Note the position of *
in the above definitions. A slight mistake such as these:
void (MyClass::*OnRequest)(); //notice the difference
void (MyClass::*OnReceive)(int); //notice the difference
would change the meaning completely! Now these are pointers-to-non-static-member-function. So know the difference and be careful. :-)
Upvotes: 1