Pointer to participants from Bruce Eckel Thinking in C ++

The following is a paragraph from Bruce Eckel, "Thinking in C ++" (Volume 1, 2nd Edition, Chapter 11) under the heading "Pointers to Participants":

... the pointer needs an address, but there is no "address" inside the class; selecting a member of a class means an offset to that class. You cannot create an actual address until you combine this offset with the start address of a specific object. The member pointer syntax requires that you select an object at the same time that the member pointer is dereferenced.

What does this quote mean? I am trying to do something like:

&(objectname.member_variable) 

I get the actual address, something like 0x22f14 , but this offset means how far is it from the starting address?

+4
source share
2 answers

I think &(foo.bar) is just a regular variable pointer. When we say "member pointer", we mean something like &(FooClass::bar) , without specifying any objects! Note that this value can actually be computed at compile time and can be used, for example. in templates.

Member pointers have really strange syntax.

Try running the following code:

 #include <stdio.h> class FooClass { public: int bar; int bar2; FooClass() : bar(0), bar2(0) {} }; int main() { //Showing what member pointers actually hold: int FooClass::* barPtr=&FooClass::bar; int FooClass::* bar2Ptr=&FooClass::bar2; printf("barPtr=%p\nbar2Ptr=%p\n",barPtr,bar2Ptr); //Showing how to use them: FooClass foo; foo.*bar2Ptr=42; printf("foo={%d,%d}\n",foo.bar,foo.bar2); } 

You will get the result:

 barPtr=0x0 bar2Ptr=0x4 foo={0,42} 

As you can see, both values ​​have a member offset from the start of the class. They can be calculated even if you don’t know which object you are working on.

But if you want to dereference them, you must provide an object - what the operator does .* .

+6
source

Yes, in this case, the term offset means how far this particular member is stored in memory from the first member of this class (which is the location of the object).

The value you get as the result is the memory position for the member * member_variable *. For visualization purposes, if you want to know the offset in bytes, you can do something like this:

 std::cout << reinterpret_cast<char *>(&(objectname.member_variable)) - reinterpret_cast<char *>(&objectname); 
0
source

Source: https://habr.com/ru/post/1342406/


All Articles