Is printing of a member pointer to an int defined

153 Views Asked by At

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?

2

There are 2 best solutions below

1
On BEST ANSWER

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.

0
On

The key issue at hand is that a pointer-to-member cannot be converted to void*, which is what the overload that usually handles printing pointers takes.

Thus, the next best conversion is used, which is the conversion pointer->bool. Both pointers are not null pointers, thus you get the output you see.

If you try printing "normal" pointers (as opposed to pointers to member), you would get the some output along the lines of what you expected initially.