|
![](/i/fill.gif) |
Darren New <dne### [at] san rr com> wrote:
> Warp wrote:
> > Darren New <dne### [at] san rr com> wrote:
> >> Warp wrote:
> >>> Isn't this usually handled with callback interfaces (in OO languages)
> >>> rather than function pointers?
> >
> >> Only in languages that don't support pointers to member functions.
> >
> > C++ supports pointers to member functions, yet using callback interfaces
> > is a rather common idiom.
> How do you declare a pointer to a member function, then? I thought you
> had to keep a pointer to the object and then somehow invoke the proper
> member function, but I don't know the syntax for that latter part?
Obviously you need an object if you want to call a member function,
be it directly or through a member function pointer. (Member functions
always require an object, as they take one as "hidden" parameter. You
can't call a member function without an object.)
Member function pointer syntax is rather complicated. If you have,
for example:
class A
{
public:
void foo(int i) { std::cout << "foo: " << i << std::endl; }
void bar(int i) { std::cout << "bar: " << i << std::endl; }
};
then you can create a member pointer named functionPointer, and make it
point to 'foo' like this:
void (A::*functionPointer)(int) = &A::foo;
(With the next C++ standard things will get easier, as you will be able
to write simply: "auto functionPointer = &A::foo;")
You can call it like this:
A a;
(a.*functionPointer)(5);
A* aPtr = &a;
(aPtr->*functionPointer)(10);
Note that this will work even if foo() is a virtual function overridden
in a class derived from A, and 'aPtr' (while still being of type A*) was
actually pointing to an object of this derived class.
Also note that 'functionPointer' is in no way tied precisely to the
foo() function. You can make it point to another member function with
the same signature:
functionPointer = &A::bar;
(a.*functionPointer)(5); // Now A::bar() is called
Curiously, you can even make pointers to member variables. That's
obscure if anything.
--
- Warp
Post a reply to this message
|
![](/i/fill.gif) |