Pointer to struct elements, print offset

Hy,
I do not understand the output of the following piece of program.
Why does o1, o2, o3 give always 1.
I would except a memory offset internal of the struct Edge.
Maybe there is something wrong with the output formating?

I would be grateful for any hint
thank you very much
dziadgba


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
using namespace std;

struct Edge
{    
    float elevation;
    float distance;
    float mode_change;
    float cost;
    float line_change;
    float co2;
};

int main()
{
  float Edge::* o1 = &Edge::elevation;
  float Edge::* o2 = &Edge::distance;
  float Edge::* o3 = &Edge::co2;

  struct Edge e;
  e.elevation = 2.0;
  e.distance = 3.0;
  e.co2 = 4.0;

  cout << e.*o1 << " " << o1 << " " << "(*o1)" << endl;
  cout << e.*o2 << " " << o2 << " " << "(*o2)" << endl;
  cout << e.*o3 << " " << o3 << " " << "(*o3)" << endl;
  
  return 0;
}

output:
2 1 (*o1)
3 1 (*o2)
4 1 (*o3)


o1, o2, and o3 are pointers to members. ostream does not have an overload that handles pointers to members,
so the compiler is finding a conversion from pointer-to-member to something that ostream can handle. The
only such conversion is to bool. A non-NULL pointer is always true (1).
Thanks!
Pointer to member is the keyword.

I could not figure out how to output the value of o1, o2. How would you do that?
You cannot do that easily.

Many programmers would simply cast the pointer to, say, a void* and output that, however
the standard makes no guarantee that sizeof a pointer-to-member be equal to sizeof ( void* )
(and indeed likely it is not).

Good bet? Take the address of o1, reinterpret_cast the address to an unsigned char*, then
output sizeof( o1 ) bytes in hex beginning at that address (though you will need to account for
machine endianness).

Best bet? Don't bother.
:-)
Thanks!

Topic archived. No new replies allowed.