|
-
April 15th, 2008, 02:38 PM
#1
Function Pointers in Classes
I have made class in c++ which has a function pointer.This function pointer needs to point to a function which is not a part of the class's methods i.e. a function that is in the main cpp.The address of the function to which the pointer points to is passed form the main cpp.However i am unable to get this to work i.e. i cannot store the address of the function in the function pointer as the function pointer has that additional "*this" pointer.I cannot make the function pointer static as each object 's function pointer points to a different function.Any fixes for this problem.
Program looks like this
class A
{
private:
void (*fnpointer)();
public:
void SetPointer(void (*fn)())
{
fnpointer=fn; //ERROR IS HERE.I DONT WANT TO MAKE fnpointer A STATIC FUNCTION
}
}
Main CPP
void func()
{
}
void main
{
A obj1;
obj1.SetPointer(&func);
}
-
April 15th, 2008, 02:54 PM
#2
Re: Function Pointers in Classes
If you can use boost then try boost::bind.
-
April 15th, 2008, 04:25 PM
#3
Re: Function Pointers in Classes
Strange, this console app compiles and runs fine using VC2005
Code:
#include "stdafx.h"
class A
{
private:
void (*fnpointer)();
public:
void SetPointer(void (*fn)())
{
fnpointer=fn; //ERROR IS HERE.I DONT WANT TO MAKE fnpointer A STATIC FUNCTION
}
void Run()
{
fnpointer();
}
};
void func()
{
printf( "Hello\n" );
}
int _tmain(int argc, _TCHAR* argv[])
{
A obj1;
obj1.SetPointer(func);
obj1.Run();
return 0;
}
Are you using an older version of VC?
-
April 15th, 2008, 06:29 PM
#4
Re: Function Pointers in Classes
 Originally Posted by blastingblast
i cannot store the address of the function in the function pointer as the function pointer has that additional "*this" pointer.
No, that makes no sense. The function pointer is declared in that code as a regular function pointer, not as a pointer to member function. Either your compiler is really messed up or you are not posting the real code.
-
April 16th, 2008, 01:45 AM
#5
Re: Function Pointers in Classes
Thanks for the replies.Yeah I managed to solve the problem. As the real program was a bit long I posted a short skeleton of the program.My mistake was that i was doing something not required by trying to make the pointer point to a member function.I managed to fix this now.THANKS AGAIN.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|