-2

So I'm trying to access the virtual functions values using vtable. The way I understand it is that the compiler creates a pointer to the vtable, and a vtable is created for each class that contains a virtual function. I was able to get the values for the first two members. Now I don't understand how go about getting the values for 'bar' function.

#include <cstdio>
#include <iostream>


class Thing
{
private:
    int x;
    int y;
    virtual int foo()
    {
        return x+y;
    }
    virtual int bar()
    {
        return x*y;
    }
public:
    Thing(){
        x = 2;
        y = 10;
    }
};

int extract_x(void *thing)
{
    // --- Begin your code ---
    char* ptrA = (char*)thing;
    ptrA=ptrA+8;
    return *ptrA;


    return 0;
    // --- End your code   ---
}

int call_bar(void* thing)
{
    // --- Begin your code ---

    // --- End your code   ---
    return 0;
}

int main()
{
    Thing thing;
    std::printf("%d  %d\n",
                extract_x(&thing),
                call_bar(&thing));
    return 0;
}
MrBiscuit
  • 51
  • 1
  • 2
  • 8

1 Answers1

2

What you're trying to do is either unsupported/undefined, or if it is defined - quite imprudent. If A is a base class of B, and you believe your A* ptr is actually a B*, just use dynamic_cast<B*>(ptr) and access the B methods like a civilized human being... (but check the result the cast for being nullptr, in case it wasn't a B* after all.)

einpoklum
  • 118,144
  • 57
  • 340
  • 684