Article View: alt.comp.lang.learn.c-c++
Article #325Re: why (ptr ->* funcPtr) () and not (ptr -> *funcPtr) () ?
From: Chris Newton
Date: Sat, 15 Jul 2000 00:00
Date: Sat, 15 Jul 2000 00:00
52 lines
2553 bytes
2553 bytes
kristofer stenberg <kristofer.stenberg@chello.se> wrote...
> Say I have an object Dog and a method Dog::run().
> ptr is a pointer to Dog and funcPtr is pointer to run().
> First I try to call run() with (ptr ->* funcPtr) () and
> it works fine. Then I try (ptr -> *funcPtr) () and its an
> error. A space between -> and * shouldnt make a
> difference, should it?
Yep, it certainly should! :-)
The key here is that a pointer-to-member is different from an ordinary
pointer. Suppose I have a function:
void F() { /* do something */ }
Here a pointer to F has type void (*)(). Now, suppose I have a class C
with a member function:
class C
{
void F() { /* do something */ }
};
In this case, a pointer to F has type void (C::*)(). Notice the C:: in
there; this is a pointer-to-member (of C), which is a different type
from a normal pointer.
Now, to dereference a normal pointer, you use the * operator. To call a
method through a pointer-to-member, and tell C++ which object you wish
to call that method on, you need a different operator. C++ provides the
operators .* and ->* for this purpose. The notation is fairly hideous at
first, but you get used to it.
So, (object_ptr->*method_ptr)() calls a method pointed to by method_ptr
on the object pointed to by object_ptr. Example:
class C
{
void method();
};
C *object_ptr; // Can point to a C object
void (C::*method_ptr)(); // Can point to C::method
(object_ptr-> *function_ptr)() would call a normal function (not a
method) pointed to by function_ptr, which would need to be a member of
the object pointed to by object_ptr. Example:
void function() { /* do something */ }
class C
{
void (*function_ptr)(); // Can point to function
};
C *object_ptr; // Can point to a C object
I hope that makes some sense! :-)
Regards,
Chris
Technical Details
Message-ID:
<8kpfub$mjq$1@neptunium.btinternet.com>Path:
arc1-ca.pugleaf.net!unknown!not-for-mailReferences:
<daLb5.765$u21.189364@nntp1.chello.se>Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: f8d38,3b2a10a91b8e07af X-Google-Attributes: gidf8d38,public X-Google-Thread: 114592,3b2a10a91b8e07af X-Google-Attributes: gid114592,public From: "Chris Newton" <chrisnewton@no.junk.please.btinternet.com> Subject: Re: why (ptr ->* funcPtr) () and not (ptr -> *funcPtr) () ? Date: 2000/07/15 Message-ID: <8kpfub$mjq$1@neptunium.btinternet.com> X-Deja-AN: 646649492 References: <daLb5.765$u21.189364@nntp1.chello.se> X-Priority: 3 X-MimeOLE: Produced By Microsoft MimeOLE V5.00.2314.1300 Organization: BT Internet X-MSMail-Priority: Normal Newsgroups: alt.comp.lang.learn.c-c++,borland.public.cpp.language