First of all, I would like to thank bolow for his question raised in my blog [C ++ Basics] 028 _ getting pointers to class member functions. I have discussed with bolow and obtained the following answers.
First, let's look at the following program:
1 #include <iostream> 2 using namespace std; 3 class A 4 { 5 public: 6 int i; 7 A():i(0){}; 8 int foo(){return i;} 9 };10 11 class B12 {13 public:14 int j,k;15 B():j(1),k(2){}16 int foo(){return k;}17 };18 19 typedef int (B::*BFPTR)();20 int main()21 {22 int (A::*fptr)()= &A::foo;23 BFPTR bfptr1=(BFPTR) fptr;24 B b;25 A a;26 cout<<(b.*bfptr1)()<<endl;27 }
22 int (A: * fptr) () = & A: Foo; give the foo address of function A as a function pointer of the Class 23 bfptr bfptr1 = (bfptr) fptr; tell the compiler to regard the above function pointer as B's function pointer (function pointer of A to function pointer of B) 24 B; 25; 26 cout <(B. * bfptr1) () <Endl; execute the function pointer of B. In fact, at this time, the foo function of A is called.
Output result:
1
Here comes the fact that the so-called class has no member functions at all. From the memory layout, we can see that the memory layout only contains the member variable space, and there is no member function memory space.
Why? You need to know how member functions are called.
Let's look at the call of the member function: object. member function () or object pointer-> member function ()
How is a member function actually declared by the compiler? For example, a member function (class, parameter) has the following classes:
1 class A{2 public:3 void foo(int a, int b){4 5 }6 private:7 int value;8 };
In fact, the above class is actually declared as follows:
1 class A{2 private:3 int value;4 };5 6 void foo(void *ptr, int a, int b){7 8 }
When we call a. Foo (1, 2), it is actually in the following form:
1 void foo(void *ptr, int a, int b){...
It can be seen that the so-called. operator actually passes the this pointer to the function Foo.
Why does the first program output 1? When a member function returns a member variable, it only returns the offset of the first address of the object. Therefore, the first parameter 1 is returned.
If Class A has three parameters and function Foo returns the third parameter, the output result is not predictable.