Home > Back-end >  A reference to a class member
A reference to a class member

Time:03-18

A reference to a class member is kind of an offset relative to the class. If I understood everything correctly. But why is 1 always output here?

#include <iostream>

struct user
{
  int id;
  double name;
  std::string last;
};


template<class V>
void kek(V b)
{
  std::cout << b << std::endl;
}

int main()
{
  kek(&user::id);
  kek(&user::name);
  kek(&user::last);
}

DEMO

CodePudding user response:

&foo::bar is a pointer-to-member. There are no references-to-members.

cout can't print member pointers directly, the closest thing it can print is bool. Your pointer was converted to bool, and since it was non-zero, you got true.

If you want to get an offset from a pointer-to-member, you could try std::bit_casting it to std::size_t, but note that it's not guaranteed to work.

But if you just want an offset to a hardcoded member, use offsetof. (thanks @TedLyngmo)

  •  Tags:  
  • c
  • Related