Skip to content

Instantly share code, notes, and snippets.

@phlash
Created September 8, 2021 00:48
Show Gist options
  • Save phlash/4dbdfefb91e802fa35afc1142cfe2cfe to your computer and use it in GitHub Desktop.
Save phlash/4dbdfefb91e802fa35afc1142cfe2cfe to your computer and use it in GitHub Desktop.
Obtaining a pointer directly to a virtual member function in a C++ class
#include <stdio.h>
class Base {
public:
virtual void DoThing() { puts("Base::DoThing"); }
virtual void *GetAddress() { void (Base::*p)() = &Base::DoThing; return (void *)p; }
};
class Derived : public Base {
public:
void DoThing() { puts("Derived::DoThing"); }
void *GetAddress() { void (Derived::*p)() = &Derived::DoThing; return (void *)p; }
};
void showMe(Base& b) {
printf("addr=%p\n", b.GetAddress());
}
int main() {
Derived d;
showMe(d);
return 0;
}
# Build disp and dump some info
disp: disp.cc
g++ -o $@ -no-pie $<
dump: disp
./disp
nm disp |fgrep DoThing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment