473,721 Members | 2,046 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Pointer to non-static member functions

Hi,

I'm experimenting with function pointers and found
two questions. Let's assume this code:

1 #include <iostream>
2 class A;
3
4 ////////////////////////////////////////////
5 class B
6 {
7 public:
8 void printB( void (A::*)(void) );
9 };
10
11 void B::printB( void (A::*func)(void ) )
12 {
13 *func(); // not working
14 }
15
16 ////////////////////////////////////////////
17 class A
18 {
19 public:
20 void printA(void);
21 void invokeB(void);
22
23 private:
24 B myB;
25 };
26
27 void A::printA(void)
28 {
29 std::cout << "A::print" << std::endl;
30 return;
31 }
32
33 void A::invokeB(void )
34 {
35 myB.printB( &A::printA );
36 return;
37 }
38
39 ////////////////////////////////////////////
40 int main(void)
41 {
42 A myA;
43 a.invokeB();
44
45 return 0;
46 }

What I want to achieve is a communication between two object
with a callback function. Object A invokes a function in
object B passing a callback function. The invoked function in
object B calls the passed callback function to communicate
with the caller A.

So, I'm passing a pointer to A::printA in line 35 to
B::printB. The called member function printB of object
myB than should deference the passed function pointer
(line 13, not working yet) to invoke again a function
(A::printfA) of the original caller. Thus, myA invokes
myB which in turn invokes myA again.

My first question concerns line 35. What exactly is the
address of &A::printA? When I forward this value to "cout",
(cout << &A::printA) I get the output "1" and not an
address. Since A::printA is a non-static member function,
it cannot be considered independent of a concrete object.
Thus, I would assume that &AA::printA is an offset which
must be added to the memory address where a concrete
object of class A is allocated. Adding the start address
and the offset would result in the address where the
function printA of an individual object of class A is
located.

And this brings me to my second question concerning line
13. When I try to compiler this code, I get the compiler error:
error: must use .* or ->* to call pointer-to-member function in `func (...)'
I assume the problem is that the function pointer "func" has
no reference to a concrete object of class A (myA in this case).
So, the function cannot be invoked. How can I solve this?
Do I have to pass the address of myA to B::printB?
Something like "myB.printB ( &A::printA, this );" in line 35
and than use the pointer in "this" to invoke func?

Thank you.

Regards,
Tim
Jun 27 '08 #1
5 4656
On 8 Maj, 11:26, Tim Frink <plfr...@yahoo. dewrote:
Hi,

I'm experimenting with function pointers and found
two questions. Let's assume this code:

* 1 #include <iostream>
* 2 class A;
* 3
* 4 ////////////////////////////////////////////
* 5 class B
* 6 {
* 7 * public:
* 8 * * void printB( void (A::*)(void) );
* 9 };
*10
*11 void B::printB( void (A::*func)(void ) )
*12 {
*13 * *func(); // not working
*14 }
*15
*16 ////////////////////////////////////////////
*17 class A
*18 {
*19 * public:
*20 * * void printA(void);
*21 * * void invokeB(void);
*22
*23 * private:
*24 * * B myB;
*25 };
*26
*27 void A::printA(void)
*28 {
*29 * std::cout << "A::print" << std::endl;
*30 * return;
*31 }
*32
*33 void A::invokeB(void )
*34 {
*35 * myB.printB( &A::printA );
*36 * return;
*37 }
*38
*39 ////////////////////////////////////////////
*40 int main(void)
*41 {
*42 * A myA;
*43 * a.invokeB();
*44
*45 * return 0;
*46 }

What I want to achieve is a communication between two object
with a callback function. Object A invokes a function in
object B passing a callback function. The invoked function in
object B calls the passed callback function to communicate
with the caller A.

So, I'm passing a pointer to A::printA in line 35 to
B::printB. The called member function printB of object
myB than should deference the passed function pointer
(line 13, not working yet) to invoke again a function
(A::printfA) of the original caller. Thus, myA invokes
myB which in turn invokes myA again.

My first question concerns line 35. What exactly is the
address of &A::printA? When I forward this value to "cout",
(cout << &A::printA) I get the output "1" and not an
address.
Probably you did print "true" because the memberfunction is not null.
Apart from that, I do not see what interest you could have in getting
its adress. If it is out of curiosity, I would recommend you to
examine the value in a debugger instead.
Since A::printA is a non-static member function,
it cannot be considered independent of a concrete object.
Yes it can. A memberfunction is not connected to any concrete object.
I will come back to that later.
Thus, I would assume that &AA::printA is an offset which
must be added to the memory address where a concrete
object of class A is allocated. Adding the start address
and the offset would result in the address where the
function printA of an individual object of class A is
located.
I am not sure I can decipher the above, but if your understanding is
that a memberfunction somehow is placed inside an object, your
understanding is wrong. A memberfunction is does not take up any space
in an object.
>
And this brings me to my second question concerning line
13. When I try to compiler this code, I get the compiler error:
error: must use .* or ->* to call pointer-to-member function in `func (...)'
(repeating offensive code)
11 void B::printB( void (A::*func)(void ) )
12 {
13 *func(); // not working
14 }
15
This is because your perception of a member-function pointer is wrong.
A member-function pointer is a pointer that can be used to call a
memberfunction oon all objects of the given type. But you have to
provide an object. So your code should have been somewhat like:
11 void B::printB( A *a, void (A::*func)(void ) )
12 {
13 (a->*func)();
14 }
15
I assume the problem is that the function pointer "func" has
no reference to a concrete object of class A (myA in this case).
So, the function cannot be invoked. How can I solve this?
Do I have to pass the address of myA to B::printB?
Something like "myB.printB ( &A::printA, this );" in line 35
and than use the pointer in "this" to invoke func?
Exactly.
/Peter
Jun 27 '08 #2
Tim Frink kirjoitti:
How can I solve this?
Use C-style functions. Another option is that you start programming
in C++ and stop using function pointers.
Jun 27 '08 #3
On May 8, 11:26*am, Tim Frink <plfr...@yahoo. dewrote:
What I want to achieve is a communication between two object
with a callback function. Object A invokes a function in
object B passing a callback function. The invoked function in
object B calls the passed callback function to communicate
with the caller A.
You might want to check out the visitor design pattern to achieve the
same effect.

Best Regards,
Szabolcs
Jun 27 '08 #4
I'm experimenting with function pointers and found
two questions. Let's assume this code:
1 #include <iostream>
2 class A;
4 ////////////////////////////////////////////
5 class B
6 {
7 public:
8 void printB( void (A::*)(void) );
9 };
10
11 void B::printB( void (A::*func)(void ) )
12 {
13 *func(); // not working
That's because you need an object on which to call the function.
14 }
15
16 ////////////////////////////////////////////
17 class A
18 {
19 public:
20 void printA(void);
21 void invokeB(void);
23 private:
24 B myB;
25 };
27 void A::printA(void)
28 {
29 std::cout << "A::print" << std::endl;
30 return;
31 }
33 void A::invokeB(void )
34 {
35 myB.printB( &A::printA );
36 return;
37 }
39 ////////////////////////////////////////////
40 int main(void)
41 {
42 A myA;
43 a.invokeB();
45 return 0;
46 }
What I want to achieve is a communication between two object
with a callback function. Object A invokes a function in
object B passing a callback function. The invoked function in
object B calls the passed callback function to communicate
with the caller A.
Are the types known to both objects? The "usual" solution here
involves an abstract base class, something like:

class AbstractCallbac k
{
public:
virtual ~AbstractCallba ck() {}
virtual void notify() = 0 ; // or some other name.
} ;

The class requesting the callback can then derive from this;
often, you migth also provide a templated concrete derivation:

template< typename T, void (T::*fnc)() >
class Callback : public AbstractCallbac k
{
public:
Callback( T* obj ) : myObj( obj ) {}
virtual void notify()
{
(myObj->*fnc)() ;
}

private:
T* myObj ;
} ;

In the absense of garbage collection, this solution requires
some complex memory management, however.
So, I'm passing a pointer to A::printA in line 35 to
B::printB. The called member function printB of object myB
than should deference the passed function pointer (line 13,
not working yet) to invoke again a function (A::printfA) of
the original caller. Thus, myA invokes myB which in turn
invokes myA again.
My first question concerns line 35. What exactly is the
address of &A::printA?
A pointer to member function. Which is more of a selector than
a pointer in the real sense. At any rate, it definitely must
contain more than just an address, since it must work with
virtual functions (where the actual function called depends on
the dynamic type it is being called on). If you check the
sizeof a pointer to member function, it will typically (but not
necessarily) be larger than a normal pointer to function.
When I forward this value to "cout", (cout << &A::printA) I
get the output "1" and not an address.
There is no << operator defined for pointer to members. There
is an implicit conversion of pointers to members to a bool,
which results in true if the pointer to member is not null, and
there is a << operator for bool.
Since A::printA is a non-static member function, it cannot be
considered independent of a concrete object. Thus, I would
assume that &AA::printA is an offset which must be added to
the memory address where a concrete object of class A is
allocated.
It's more complicated than that. The class instance doesn't
actually contain a copy of the code of its member functions; in
many ways, the only difference between a member function and a
non member function is that the member function has an
additional hidden argument. The way member functions are
called, however, is different, both in regards to syntax, and
(at least when virtual functions are considered) the mechanics.
Adding the start address and the offset would result in the
address where the function printA of an individual object of
class A is located.
No.
And this brings me to my second question concerning line 13.
When I try to compiler this code, I get the compiler error:
error: must use .* or ->* to call pointer-to-member function
in `func (...)' I assume the problem is that the function
pointer "func" has no reference to a concrete object of class
A (myA in this case). So, the function cannot be invoked. How
can I solve this? Do I have to pass the address of myA to
B::printB? Something like "myB.printB ( &A::printA, this );"
in line 35 and than use the pointer in "this" to invoke func?
Exactly. Or you wrap some, using an intermediate "agent" class.
(This is generally considered the prefered solution, since it
means that the class invoking the callback doesn't need to know
of the class which is called back.)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #5
>
Probably you did print "true" because the memberfunction is not null.
But why did I not get the address? I though that &A::printA is a pointer.
So, I can't understand why I get "true".
Apart from that, I do not see what interest you could have in getting
its adress. If it is out of curiosity, I would recommend you to
examine the value in a debugger instead.
This was just for curiosity. When this value is passed as an
argument, it would make sense to check if it's not 0. So I think
that the check of the address makes sense in some situations.
I am not sure I can decipher the above, but if your understanding is
that a memberfunction somehow is placed inside an object, your
understanding is wrong. A memberfunction is does not take up any space
in an object.
I'm not aware of the code generation for C++ programs. But from your
post I assume that for each C++ class exactly one code (fragment) is
allocated in the object's text section independently if and how many
times objects of this class are instantiated. So what happens when
an object of a particular class is instantiated? Will additional code
be allocated in the .text section? Or will this new object be considered
as data allocated on the stack/heap with some references to the class
code located somewhere in the .text section?
>And this brings me to my second question concerning line
13. When I try to compiler this code, I get the compiler error:
error: must use .* or ->* to call pointer-to-member function in `func (...)'

(repeating offensive code)
> 11 void B::printB( void (A::*func)(void ) )
12 {
13 *func(); // not working
14 }
15

This is because your perception of a member-function pointer is wrong.
A member-function pointer is a pointer that can be used to call a
memberfunction oon all objects of the given type. But you have to
provide an object. So your code should have been somewhat like:
So, why do I need the object and can't access the function (in my
case func) without the object? If it's already in the memory
(.text section) and func has the address to it, so why is the
object still needed for the access?

My assumption would be that an instantiated object has some references
which point to addresses (or functions/attributes behind theses addresses)
that is is allowed to access. So, the object code contains a sort
of permissions about what code can be accessed and which not. Are these
thoughts going into the right direction?

Tim
Jun 27 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
2061
by: Chris Mantoulidis | last post by:
I see some really weird output from this program (compiled with GCC 3.3.2 under Linux). #include <iostream> using namespace std; int main() { char *s; s = "test1"; cout << "s = " << s << " and &s = " << &s << "\n";
6
1842
by: amparikh | last post by:
I know this is something fundamental and I ought to have known it, but somehow this seems to be confusing me a lot. Fundamentally, rvalues and/or temporaries can be bound only to constant references going by the const guidelines. Taking that into consideration, how does one get a constant reference to a pointer. class A
110
9934
by: Mr A | last post by:
Hi! I've been thinking about passing parameteras using references instead of pointers in order to emphasize that the parameter must be an object. Exemple: void func(Objec& object); //object must be an object instead of
204
13038
by: Alexei A. Frounze | last post by:
Hi all, I have a question regarding the gcc behavior (gcc version 3.3.4). On the following test program it emits a warning: #include <stdio.h> int aInt2 = {0,1,2,4,9,16}; int aInt3 = {0,1,2,4,9};
9
5867
by: uotani.arisa | last post by:
Hi, Can someone tell me how to declare a pointer to a vector of pointers? I'm just not sure how to do this... I've tried essentially the following: vector<string *> * v; ....
17
2717
by: Christian Wittrock | last post by:
Hi, What does ANSI C say about casting an 8 bit pointer to a 16 bit one, when the byte pointer is pointing to an odd address? I have detected a problem in the Samsung CalmShine 16 compiler. This compiler I use for the Samsung 16 bit Smartcard chips and I want to know if it is compliant with the ANSI standard or if it violates it. Have a look at this super simple example, where the value of b is incorrect:
10
407
by: Michael | last post by:
Hi, I'm trying to get my head around the relationship between pointers and arrays. If I have the following: int even = {2,4,6,8,10}; int *evenPtr = {even+4, even+3, even+2, even+1, even}; int **ip = evenPtr+3;
33
5064
by: Ney André de Mello Zunino | last post by:
Hello. I have written a simple reference-counting smart pointer class template called RefCountPtr<T>. It works in conjunction with another class, ReferenceCountable, which is responsible for the actual counting. Here is the latter's definition: // --- Begin ReferenceCountable.h ---------- class ReferenceCountable
19
3899
by: =?iso-8859-1?b?VG9t4XMg0yBoyWlsaWRoZQ==?= | last post by:
Coming originally from C++, I used to do the likes of the following, using a pointer in a conditional: void Func(int *p) { if (p) { *p++ = 7; *p++ = 8;
1
375
by: Carmen Sei | last post by:
to delcare an object with pointer - MyCar * mycar = new MyCar; mycar->Create(); ======================== to delcare an object without pointer - MyCar mycar = new MyCar; mycar.Create(); ========================
0
8736
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9373
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9142
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8016
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6676
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5992
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4493
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4761
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2587
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.