Question

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.

Était-ce utile?

La 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 :-)

Autres conseils

There is no guarantee by standard, that virtual functions are implemented using v-table. So, only if you are sure, that compiler use v-table - you can find needed offset.

Portably, no. The language doesn't specify how virtual dispatch is implemented, only how it behaves. It is not necessarily implemented using a v-table, and there is no way to access a virtual function except to call it.

If you only need to support one particular ABI, then you could use the implementation details, along with some dodgy pointer casts, to map an object to a function pointer in the same way that the virtual dispatch mechanism does. But you'll be stepping outside the defined language into unsupported, non-portable territory, so I would definitely recommend rethinking whatever you're trying to do.

I'd say no in general, because the exact implementation of the vtable is a platform/compiler specific. If you know how the platform/compiler implements the vtable and the addresation, it might be possible to compute it by determining the address of a vtable for a specific class and then adding a offset of a virtual method.

The vtable contains all the virtual methods for the class. You can disassemble the application to see them.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top