I have some further findings.
1.
It seems a debugger bug. I have found the address of the vtable of class
You can try it by "Watch Memory" of the base address of vtable. To my
Well... Seems reasonable from first look. But how do you explain class Zoo
zoo_func is still in vtable of Zoo. :-)
So, my conclusion is it is a bug of debugger. And easy to reproduce.
George wrote:
Hi Bo Persson,
Great reply!
Where is class Derived's own __vfptr (points to its own virtual
methods)? From debugging, I can not find it out by adding a new
method in Derived which is not in Foo and Goo.
I belive you have actually found Derived's __vfptr. As there aren't
any separate Foo or Goo objects, there own vtable pointers need
not be present in the resulting executable. Or perhaps one of them
is?
I have made the sample easy to show that the non-override methods
-- even if virtual is not in vtable. I am very confused.
Here is the code and result, and I am using Visual Studio 2008. In
class Goo, there are three virtual methods
- virtual int func1() {return 0;}
- virtual int func2() {return 0;}
- virtual int myFunc() {return 1;}
But in vtable of Goo class object, you can only find func1 and
func2.
As long as no class derives from Goo, we all know what function is
really called, and there is no need for a vtable. Apparently, the
compiler might then save the unneeded space for an extra function
pointer. Good if it does!
In class Zoo, there is only one virtual method called zoo_func, and
it is in vtable of Zoo class object.
There is a huge difference between having and not having a vtable
pointer!
Other features, like typeinfo and dynamic_cast, might also use it.
There is a requirement that the class should have at least one virtual
function for them to work. Now you know why!
Sometimes we add an empty virtual destructor to a base class, just to
provoke a vtable (or whatever the compiler uses) for the class.
Why myFunc is missing in vtable of Goo?
There is just one myFunc in the program, so the compiler knows which
one to call anyway.
Bo Persson
Here is my complete code. Easy program to understand and debug. :-)
#include <iostream>
using namespace std;
class Foo {
virtual int func1() = 0;
virtual int func2() = 0;
virtual int func3() {return 0;}
};
class Goo: Foo {
public:
virtual int func1() {return 0;}
virtual int func2() {return 0;}
virtual int myFunc() {return 1;}
};
class Zoo {
public:
virtual int zoo_func() {return 0;}
};
int main()
{
Goo g;
Zoo z;
return 0;
}
regards,
George