Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Virtual function from V-table [closed]

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.

like image 987
Kushagra Jaiswal Avatar asked Jun 14 '13 10:06

Kushagra Jaiswal


People also ask

When should you not call a virtual member function?

15 Answers. Show activity on this post. Calling virtual functions from a constructor or destructor is dangerous and should be avoided whenever possible. All C++ implementations should call the version of the function defined at the level of the hierarchy in the current constructor and no further.

Can I call virtual function from constructor?

You can call a virtual function in a constructor. The Objects are constructed from the base up, “base before derived”.

Can you call virtual function?

A virtual function is a member function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.

Is virtual function call is resolved at runtime?

Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for function call. Functions are declared with a virtual keyword in base class. The resolving of function call is done at runtime.


2 Answers

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

like image 116
user1764961 Avatar answered Sep 22 '22 07:09

user1764961


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.

like image 42
ForEveR Avatar answered Sep 23 '22 07:09

ForEveR