c++coutmember-pointers

Is printing of a member pointer to an int defined


Suppose I have this code:

#include <iostream>

struct Mine
{
    int a;
    int b;
};


int main()
{

    int Mine::* memberPointerA = &Mine::a;
    int Mine::* memberPointerB = &Mine::b;



    std::cout << memberPointerA;
    std::cout << "\n";
    std::cout << memberPointerB;
}

When I run this with Microsoft Visual C++ (2015)

I get the following output

1
1

The output I expect is something more like this:

1
2

So this begs the question: Is this printing of a member pointer defined behavior?


Solution

  • There's a defined conversion from pointer to bool. Since the member variable pointers are not NULL, they evaluate as true and print as 1.