Search code examples
c++virtual-functionsvtable

Calling Virtual function from V-table


As all the virtual function in C++ is stored in V-table. Overiding takes place in the case of virtual function. I want to ask there is any way by which we can call the Virtual function directly from the table and able too determined what functions V-table contains.


Solution

  • Well, actually you can. I don't care about portability, but in VS you can do it. Assuming that we are building 32-bit code with VS, the first 4 bytes at the objects address is the vtable address. By looking at the header files we know the order of 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;
    }
    

    P.S. I'm not going to ask why are you doing it, but here you have one option :-)