Skip to content

Instantly share code, notes, and snippets.

@IlyaSkriblovsky
Last active January 10, 2019 20:57
Show Gist options
  • Save IlyaSkriblovsky/0bbe56830acbfcf543ebf38fcc8b7ddc to your computer and use it in GitHub Desktop.
Save IlyaSkriblovsky/0bbe56830acbfcf543ebf38fcc8b7ddc to your computer and use it in GitHub Desktop.
#include <cstdio>
class A {
public:
int x;
A(int x): x(x) {}
};
class B: public A {
public:
B(int x): A(x) {}
virtual void f();
};
void B::f() {}
void dump_bytes(const void *ptr, int n = 12) {
const unsigned char *bytes = (const unsigned char*)ptr;
for (int i = 0; i < n; i++)
printf("%02x ", bytes[i]);
printf("\n");
}
int main() {
A a(5);
printf("&a: ");
dump_bytes(&a); // &a: 05 00 00 00 a0 99 4f 68 b4 7f 00 00
B b(5);
printf("&b: ");
dump_bytes(&b); // &b: 68 ad 23 4d a0 55 00 00 05 00 00 00
printf("\n");
A *pb = &b;
printf("pb->x = %d\n", pb->x); // 5
A *rpb = reinterpret_cast<A*>(&b);
printf("rpb->x = %d\n", rpb->x); // 1294183784
printf("\n");
printf("&b = %p\n", &b); // 0x7fffe0703e10
printf("(u8*)&b = %p\n", (unsigned char*)&b); // 0x7fffe0703e10
printf("(A*)&b = %p\n", (A*)&b); // 0x7fffe0703e18
printf("reinterpret_cast<A*>(&b) = %p\n", reinterpret_cast<A*>(&b)); // 0x7fffe0703e10
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment