Jeff
Jeff

Reputation: 463

Cannot find the virtual function address of derived class in virtual function table

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

Upvotes: 0

Views: 484

Answers (1)

Yirkha
Yirkha

Reputation: 13818

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

Upvotes: 1

Related Questions