tags:

views:

82

answers:

3

Can I have, as a private member of a class, an array of function pointers? Something like,

class MyClass {
public: //public stuff

private:
void (*specficFunctions[16]) (void);
}

I specifically don't want to use functors or functionoids.

+2  A: 

There's nothing special about function pointers. The declaration syntax may be confusing (which can be mitigated with typedefs) but they're not really different from any other pointer. If you can make an array of pointers, you can make an array of function pointers. There's also nothing special about a private member of a class compared with any other type of variable. If you can make an array, you can make an array a private member of a class.

Cogwheel - Matthew Orlando
I realized after the fact that the 'private' part was not an important part of it. As I recall, member functions compile with an implicit reference to 'this' object. I didn't know how that might affect function-pointers-as-members [rather than the more common pointers-to-member-functions].
David
@David: The `this` is only implicit to member _functions_, not to _data_ members.
sbi
+2  A: 

Yes, though you usually want to use a typedef to keep the syntax a bit more manageable:

class MyClass { 
    typedef void (*fptr)(void);

    fptr SpecificFunctions[16];
};

Note, however, that these are pointers to global functions, not member functions.

Jerry Coffin
Typedefs are fine, and I will use them. The thing I am [still] working on suffers from brittleness for a couple of reasons. I'm trying to isolate that brittleness into a single unit, while keeping it functional. Then I'm going to work off the problems.
David
+2  A: 

Yes. (You can always answer this kind of question by trying to compile such code.)

Nick Meyer
Compilation is not a good test of whether something is allowed in general. You may be hitting an odd compiler extension, or one of the last few incompatibilities it has with the Standard.
David Thornley
@David, good point.
Nick Meyer