Is printing of a member pointer to an int defined
Asked Answered
B

2

5

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?

Banna answered 27/7, 2017 at 23:28 Comment(0)
C
12

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.

Chophouse answered 27/7, 2017 at 23:33 Comment(1)
Oh....that makes sense (I just realized this was probably going on just as you answered)Banna
I
7

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.

Incarnadine answered 27/7, 2017 at 23:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.