Question

I write some testing code, to figure out the address about member function. But the result confuse me. the code is

#include <stdio.h>
#include <stdlib.h>
#include <iostream>

class A
{
public:
        A(char _a, char _b, char _c, char _t):a(_a), b(_b), c(_c), t(_t){}

private:
        char t;
        char a;
public:
        char b;
        char c;
        void test1(){std::cout << a << std::endl;}
        void test2(){std::cout << b << std::endl;}
        void test3(){std::cout << c << std::endl;}
        void test4(){std::cout << t << std::endl;}

        static void print(){

                char A::*pa = &A::a;
                char A::*pb = &A::b;
                char A::*pc = &A::c;
                char A::*pt = &A::t;
                printf("data member : %p, %p, %p, %p\n", pa, pb, pc, pt);

                void (A::*pf1)() = &A::test3;
                void (A::*pf2)() = &A::test2;
                void (A::*pf3)() = &A::test3;
                void (A::*pf4)() = &A::test2;
                printf("function member : %p, %p, %p, %p\n", pf1, pf2, pf3, pf4 );
        }
};

int main()
{
        A::print();

    //system("pause");//need on Dev-c++
        return 0;
}

I run this code on ubuntu with g++, and Windos with Dev-C++, the results are the same

data member : 0x1, 0x2, 0x3, (nil)
function member : 0x8048780, (nil), 0x804874e, (nil)

Why the pf2 and pf4 is nil?

Was it helpful?

Solution

Pointers to members are not regular pointers, you can test it by printing the size of the pointer to member and the size of a regular pointer. The code that you have exhibits undefined behavior, but if you want a simple explanation of the results, printf takes a variable number of arguments, which is implementing by pushing the arguments to the stack in some preconceived order and adding some extra information on what the number of arguments in the call is.

In your case, the pointer-to-member function are being pushed as they are (usually twice the size of a regular pointer), and then printf is reading the stack and interpreting the bits there as regular pointers. My guess (you would have to read the compiler/platform documentation to verify this) is that you are only printing the first two arguments, with the contents separated by commas.

A slightly better way of doing that would be to create a union of a pointer to member function and a char array of the appropriate size, initialize it with the pointer to member and print the hexadecimal values through the array.

OTHER TIPS

Why the pf2 and pf4 is nil?

Because the code shown has undefined behaviour. Pointers to member functions are not pointers (yes, yes, I know it's bad naming; such is C++), yet the printf format string is expecting pointers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top