Created
September 8, 2021 00:48
-
-
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
This file contains 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
#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; | |
} |
This file contains 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
# 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