C++ Function Pointers and Classes

Status
Not open for further replies.
G++ does not like this and won't compile. I don't know why. Rip away the class stuff and it works fine, just like any other function pointer.

Code:
class A
{
        public:
        A();
        void b(void);
};

A::A()
{
        void (*p)();
        p = b;
        (*p)();
}

void A::b(void)
{

}

main (void) { }

Code:
temp.c: In method `A::A()':
temp.c:11: no matches converting function `b' to type `void (*)()'
temp.c:5: candidates are: void A::b()

It's absolutely driving me nuts. I've tried casting to void (Error: ANSI C++ forbids casting from blah blah blah), adding a '&', prepending it with this-> or A:: or whatever.

I always wanted C++ to a great combination of my two favorite languages, C and Java, but the syntax is starting gnaw away at my mind. I try to ignore most of the ugly crap but it's stuff like this, that should work, that stops me.

Anyway, any help would be appreciated. Yeah, I google'd.
 

Edmund

Wise, Aged Ars Veteran
128
Originally posted by Kadesh:
Code:
class A
{
        public:
        A();
        void b(void);
};

A::A()
{
        void (*p)();
        p = b;
        (*p)();
}

Come on. Think about it. Your b() function is a member function of class A. It needs an object of class A to work on. It has a different signature that your function pointer.

Code:
void function();
void A::function();

If you would make the member function static then everything would work. I.e.:

Code:
class A
{
        public:
        A();
        static void b(void);
};
 
Status
Not open for further replies.