2

I have a class below:

class A
{
public:
    double a;
    float b;
    double c;
};

I want to print data member offset in class, than I use:

double A::* pm = &A::a;
cout << *(int *)&pm << endl;

It works well and print '0', but I don't want to use intermediate variable pm

cout << *(int *)&A::a << endl;

I got compile error with : Invalid type conversion

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Carl Chen
  • 21
  • 2
  • 1
    You should clarify your question since what you are printing is not an offset, offset should be the difference between the member address and the class instance address, as mentioned by @WhozCraig `std::offsetof` does that. – Rudolfs Bundulis Sep 11 '14 at 08:30
  • @RudolfsBundulis: This could be a flaky, non-portable way to print a member's offset, if that's how member pointers are represented (which is usually the case), and if a member pointer happens to have the same size as `int`. But yes, `std::offsetof` is the portable way to get an offset. – Mike Seymour Sep 11 '14 at 08:40
  • 1
    @WhozCraig I don’t believe that `std::offsetof` exists. It’s a macro, it doesn’t reside in `std`. – Konrad Rudolph Sep 11 '14 at 08:55
  • @KonradRudolph roger that. you're correct. in `cstddef`. thx for the correction. – WhozCraig Sep 11 '14 at 09:07
  • Note a pointer to data member doen't have to be the same as the offset of that member. Some compilers use a different representation. – n. m. could be an AI Sep 11 '14 at 09:23
  • Worth noting that `offsetof` has UB unless the type is standard-layout. – T.C. Sep 11 '14 at 09:47

1 Answers1

0

With offset is assumed that you refer offset in bytes.

You could try this solution:

(size_t) &(((A*)0)->a) // prints 0

Actually this is the implementation of the macro offsetof as WhozCraig suggested.

 ...
cout << "A::a => " << (size_t) &(((A*)0)->a)
     << "\nA::b => " << (size_t) &(((A*)0)->b)
     << "\nA::c => " << (size_t) &(((A*)0)->c);
 ...

Combined with your data, previous snippet will print:

A::a => 0
A::b => 8
A::c => 16
Community
  • 1
  • 1
Filippo Lauria
  • 1,965
  • 14
  • 20