This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Member function pointer woes


Hi,

I need to pass a pointer-to-member-function as a parameter to a function
which takes pointer-to-function as an argument. Is there any way to do it
besides overloading the function?

Here is a small program I wrote to check if I could get the address of the
function from the member-function-pointer, so that I could pass it to the
function as a normal function-pointer.

---------------------------------------------------
#include<stdio.h>

class classname{
 public:
  int add(int a, int b){
   printf("inside add. \ta = %d, b = %d\n", a,b);
   return a+b;
  }
}obj;


typedef int(classname::*mfptr)(int, int);
typedef int (*fptr)(int, int);


main(){

 mfptr mem_func_ptr;
 fptr func_ptr;

 mem_func_ptr = &classname::add;
 func_ptr = (fptr)(&classname::add);

 printf("&classname::add is %llx\n", &classname::add);
 printf("&classname::add is %llx\n", &classname::add);

 printf("mem_func_ptr is %llx\n", mem_func_ptr);
 printf("func_ptr is %x\n\n", func_ptr);

 printf("add called with func_ptr. sum is %d\n\n", func_ptr(2,3));
 printf("add called with mem_func_fptr. sum is %d\n\n",
(obj.*mem_func_ptr)(2,3));
}

-----------------------------------------------------


I compiled it with the -Wno-pmf-conversions option. Here is the output of
the program:

------------------------------------------
&classname::add is ffbeee78ff23e5d0
&classname::add is ffbeee78ff243a4c

mem_func_ptr is ffbeee78ff243a4c
func_ptr is 109bc

inside add.     a = 3, b = 68028
add called with func_ptr. sum is 68031

inside add.     a = 2, b = 3
add called with mem_func_fptr. sum is 5

------------------------------------------


A few questions:

1. Why is the value of '&classname::add' in the two lines different?
2. Why does the value of parameter 'b' change when 'classname::add' is
called with 'func_ptr'?
3. If this approach is not correct, then could you please advise as to how
to go about with it?

Thanks.

Albert.


-----------------------------------------------------------------------------------
This email was sent from IIT Guwahati Webmail.If you are not the intended recipient, please contact the sender by email and delete all copies; your cooperation in this regard is appreciated.
http://www.iitg.ernet.in



Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]