{"slug": "monkey-patching-a-c-class-by-modifying-its-vtable", "title": "Monkey patching a C++ class by modifying its VTABLE.", "summary": "The article demonstrates a technique called \"monkey patching\" in C++ by directly modifying an object's virtual table (vtable) at runtime. It shows how to obtain the vtable pointer from an instance of class A, then replace the function pointer for the virtual method `doThing()` with a different function (`dynamicOverride`). This change affects not only the original object but also all subsequently created instances of the class.", "body_md": "vtable.cpp\n\n      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.\n      \nLearn more about bidirectional Unicode characters\n\n \n    Show hidden characters\n\n#include <stdio.h>\n\n#include <stdint.h>\n\nclass A {\n\npublic:\n\n  virtual void doThing() {\n\n    printf(\"I'm an A\\n\");\n\n  }\n\n};\n\nvoid dynamicOverride(A* a) {\n\n  printf(\"I'm an imposter!\\n\");\n\n}\n\nint main(int argc, char *argv[]) {\n\n  A* a = new A();\n\n  // grab the vtable for the A class\n\n  void** vtable = *(void***)a;\n\n  a->doThing();\n\n  // out: \"I'm an A\"\n\n  void (A::* ptr)() = &A::doThing;\n\n  void* offset = *(void**)&ptr;\n\n  vtable[((uintptr_t)offset)/sizeof(void*)] = (void*)&dynamicOverride;\n\n  a->doThing();\n\n  // out: \"I'm an imposter!\"\n\n  // affects future instances as well\n\n  A* a2 = new A();\n\n  a->doThing();\n\n  // out: \"I'm an imposter!\"\n\n  return 0;\n\n}", "url": "https://wpnews.pro/news/monkey-patching-a-c-class-by-modifying-its-vtable", "canonical_source": "https://gist.github.com/netguy204/6097063", "published_at": "2013-07-28 02:11:51+00:00", "updated_at": "2026-05-23 18:35:45.389393+00:00", "lang": "en", "topics": ["developer-tools"], "entities": [], "alternates": {"html": "https://wpnews.pro/news/monkey-patching-a-c-class-by-modifying-its-vtable", "markdown": "https://wpnews.pro/news/monkey-patching-a-c-class-by-modifying-its-vtable.md", "text": "https://wpnews.pro/news/monkey-patching-a-c-class-by-modifying-its-vtable.txt", "jsonld": "https://wpnews.pro/news/monkey-patching-a-c-class-by-modifying-its-vtable.jsonld"}}