-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpointer_to_member.cpp
52 lines (38 loc) · 1.74 KB
/
pointer_to_member.cpp
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
class MyFabulousClass
{
public:
int firstMember;
int secondLittleLessFabulousMember;
char whatDoesACharDoHere;
float notSoFabulous;
};
using std::cout;
using std::endl;
// Let's define a pointer to member for MyFabulousClass
using PointerToLessFabulousMember = char MyFabulousClass::*;
// Implicitly would be initialized to zero nevertheless
static char MyFabulousClass::* staticPointerToMember = 0;
int main()
{
MyFabulousClass myClass;
// Both pointers below point just to a member of a class - not to any specific object!
// Not using the alias - pointing to a specific member with specified type in the MyFabulousClass class
char MyFabulousClass::* ptrToTheCharMember = &MyFabulousClass::whatDoesACharDoHere;
// Using the defined alias - this is also pointing just to a specific member with defined type in the class
PointerToLessFabulousMember secondPtrToChar = &MyFabulousClass::whatDoesACharDoHere;
// Direct access, via dot operator
myClass.whatDoesACharDoHere = 'c';
// Access by the pointer-to-member, done by the offset
myClass.*ptrToTheCharMember = 'd';
// int castedPtrValue = static_cast<int>(staticPointerToMember);
// But this probably would be truncated and then interpreted as char* during dereferencing?
// So it probably will print only the value of the first byte (char), if sizeof(int) == 4 then four such operations would be needed
int castedPtrValue = *((char*)(&staticPointerToMember));
// Yeah, operator precedence
int alternativelyCastedValue = *(int*)(&staticPointerToMember);
// Let's see the raw value of the pointer, will be equal to zero as initialized? :)
cout << castedPtrValue << endl;
cout << alternativelyCastedValue << endl;
return 0;
}