cd /news/developer-tools/monkey-patching-a-c-class-by-modifyi… · home topics developer-tools article
[ARTICLE · art-12096] src=gist.github.com ↗ pub= topic=developer-tools verified=true sentiment=· neutral

Monkey patching a C++ class by modifying its VTABLE.

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.

read1 min views21 publishedJul 28, 2013

vtable.cpp

  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.

Learn more about bidirectional Unicode characters

Show hidden characters

#include <stdio.h>

#include <stdint.h>

class A { public:

  virtual void doThing() {

    printf("I'm an A\n");

  }

};

void dynamicOverride(A* a) {

  printf("I'm an imposter!\n");

}

int main(int argc, char *argv[]) {

  A* a = new A();

  // grab the vtable for the A class

  void** vtable = *(void***)a;

  a->doThing();

  // out: "I'm an A"

  void (A::* ptr)() = &A::doThing;

  void* offset = *(void**)&ptr;

  vtable[((uintptr_t)offset)/sizeof(void*)] = (void*)&dynamicOverride;

  a->doThing();

  // out: "I'm an imposter!"

  // affects future instances as well

  A* a2 = new A();

  a->doThing();

  // out: "I'm an imposter!"

  return 0;

}
── more in #developer-tools 4 stories · sorted by recency
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
Live at https://your-agent.zahid.host
Get free account → Pricing
from €0/mo · no card required
LIVE [news/monkey-patching-a-c-…] indexed:0 read:1min 2013-07-28 ·