Skip to content

Instantly share code, notes, and snippets.

@darvil82
Last active March 29, 2024 02:48
Show Gist options
  • Save darvil82/61fd3e0df9238d872c86bcbe90fa62ec to your computer and use it in GitHub Desktop.
Save darvil82/61fd3e0df9238d872c86bcbe90fa62ec to your computer and use it in GitHub Desktop.
funny c++
#include <iostream>
#include <inttypes.h>
struct Test {
int x = 55;
virtual void test() {
printf("hello %d\n", this->x);
}
};
struct Test2 : public Test {
Test2() {
this->x = 192;
}
void test() override {
printf("goodbye %d\n", this->x);
}
};
int main() {
auto* t1 = new Test();
auto* t2 = new Test2();
void (*** t2_test_method)(Test*) = reinterpret_cast<void (***)(Test*)>(t2); // get func ptr of Test2 test()
(**t2_test_method)(t1); // call Test2 test() as a Test instance
(**t2_test_method)(t2); // call normally
struct shit_t { // to represent what a test instance would look
uintptr_t vtable_ptr_space = 0; // the virtual table pointer
int x = 255; // where x would be
} shit;
(**t2_test_method)(reinterpret_cast<Test*>(&shit)); // call the method as if shit was a Test2 instance
void (* new_vtable[])(Test*) { // create an array of function pointers
[](Test* this_) {
printf("hohoho %d", this_->x);
}
};
// make the virtual table pointer point to our array instead
*reinterpret_cast<uintptr_t*>(t2) = reinterpret_cast<uintptr_t>(new_vtable);
t2->test(); // calls hohoho
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment