Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Does Getting the Address of a Class Member Through a Scope Resolution Operator Work When Using a Pointer-to-Member?

When using a pointer-to-member (AKA dot-star or arrow-star) to access a class member, we can use the following syntax:

A * pa;
int A::*ptm2 = &A::n;
std::cout << "pa->*ptm: " << pa->*ptm << '\n';

My question is how does the &A::n statement work?

In the above example n is a variable. If instead of a member variable, n was a function (and we defined a pointer-to-a-member-function instead of a pointer-to-a-member), I might reason that since a class's functions can be effectively static (see Nemo's comment), we could find a class's function's address via &A::some_function. But how can we get the address of a non-static class member through a class scope resolution? This is even more confusing when I print the value of &A::n because the output is merely 1.

like image 449
user2141130 Avatar asked Oct 26 '25 10:10

user2141130


1 Answers

When you declare a pointer to member data, it isn't bounded to any particular instance. If you want to know the address of a data member for a given instance you need to take the address of the result after doing .* or ->*. For instance:

#include <stdio.h>

struct A
{
  int n;
};

int main()
{
  A a  = {42};
  A aa = {55};
  int A::*ptm = &A::n;
  printf("a.*ptm: %p\n", (void *)&(a.*ptm));
  printf("aa.*ptm: %p\n", (void *)&(aa.*ptm));
}

prints as one possible output:

a.*ptm: 0xbfbe268c
aa.*ptm: 0xbfbe2688
like image 68
greatwolf Avatar answered Oct 28 '25 23:10

greatwolf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!