Well, actually you can. I don't care about portability, but in VS you can do it. Assuming that we are building a 32-bit code with VS, the first 4 bytes at the address of the objects are the address of vtable. Studying the header files, we know the order of the methods in the vtable.
Example:
class Base { public: virtual void printMessage() { std::cout << "Base::printMessage()" << std::endl; } }; class Derived : public Base { public: void printMessage() { std::cout << "Derived::printMessage()" << std::endl; } }; int main(int argc, char* argv[]) { Derived d; unsigned int vtblAddress = *(unsigned int*)&d; typedef void(*pFun)(void*); pFun printFun = (pFun)(*(unsigned int*)(vtblAddress)); printFun(&d); return 0; }
PS I will not ask why you are doing this, but here you have one option :-)
user1764961
source share