0
votes

This is the source code to observe the virtual function table:

#include <iostream>
using namespace std;

class Base 
{
public:
    virtual void func() {}
    virtual ~Base() {}
protected:
    int x;
};

class Derived : public Base
{
public:
    virtual ~Derived() {}
    virtual void func2() { cout << " func2() " << endl; }
protected:
    int y;
};

int main()
{
    Base b;
    Derived d;
    cout << endl;
    return 0;
}

I use the vs2012 and debug to the "cout << endl;" statement, then I find that the member function "func2" does not appear in the virtual function table, there are only Base::func() and Derived::~Derived().

enter image description here

1
You are looking at d -> Base -> __vfptr, but Base's vtable has no need/place for func2. Check if you can find Derived's vtable.Daniel Frey
But there would be only one table which would be shared between the Base & Derived.Mantosh Kumar
This is the whole object model for object d. I cannot find other vtable.Jeff
@MantoshKumar Yes and no. The vtable, as the object itself, is extended. If you look at it through Base (as the OP did in the debugger), you only see the first part which contains all the things Base knows about. You need to look at it through Derived to see the additional slots for func2, etc. This probably means that the debugger is simply too stupid to show all the information as the vtable-ptr is stored in the Base-part of the Derived instance and when the debugger tries to show it, it looses the information that d is Derived and could therefore use Derived's vtable.Daniel Frey

1 Answers

1
votes

It seems to be just a bug or weird behavior on Visual Studio's side.

If you right-click on the __vfptr member and use "Add Watch" command in the context menu, you end up with a watch (*((Base*)(&(d)))).__vfptr,nd, showing the same.

Even if you change it to (*((Derived*)(&(d)))).__vfptr,nd, or just d.__vfptr for that matter, it still shows the same, even though Derived's vtable is bigger.

You need to explicitly specify the number of elements as 3 like this for it to finally show the rest of the table and your function: d.__vfptr,3