c++pointersmember-pointers

Why does printing address of data member of a struct enabled, although there is no object?


Suppose I have the following code. I have expected that this has to at least give me a warning.

#include <iostream>

struct test
{
    int whatever;
};

int main()
{
    int test::* p = &test::whatever;    
    std::cout << p;
}

However, I was surprised to find out that this code compiles without complaints. So I would like to know, what is actually printed in this case, how is the test::whatever stored, so we can access its address?


Solution

  • how is the test::whatever stored

    This is not specified in the language. But we can make a reasonable guess that it stores an offset from the beginning of the object to the pointed member.

    so we can access its address?

    No.

    what is actually printed in this case

    1 is printed.

    There is no operator overload for member pointers. But there is an overload for bool and member pointers are convertible to bool. They convert to true when they aren't null. p isn't null, so it converts to true which prints as 1.