Search code examples
c++inheritancevisual-studio-2012polymorphismvtable

Derived class VTable having only base class virtual functions. The derived class virtual functions are missing from derived class's vtable


Here is a very basic example:

class Base {
public:
    virtual void sayHi() const {}
    virtual void sayHello() {}
    virtual ~Base(){}
};

class Derived : public Base {
public:
    virtual void sayHi() {}
    virtual void sayHello() const {}
};

int main()
{
    Base *b = new Base();
    Base *d = new Derived();
    return 0;
}

The Base's vptr, in 'b' has virtual functions of Base class. The derived class object 'd' however, on inspection, list virtual functions of only base. The question here is not, why are the functions not being overridden so the use of override keyword isn't required here. The question is, why doesn't a particular class's VTable contain its own virtual functions? In this case why vtable of 'd' doesnt contain D::sayHi and D::sayHello? I am open to downvotes, but be brave to mention and tell the reason.

edit: I know that the CONSTness might look wrong here, but the question is not about overriding.

This is specifically tried out in VS2012 Update4


Solution

  • Here you have different function overloads that do not override the defined virtual functions:

    virtual void sayHi() const {}
    virtual void sayHello() {}
    
    void sayHi() {}  // non virtual function with a different signature (no const)
    void sayHello() const {} // non virtual function with a different signatuere (const)
    

    If you want to avoid such subtle errors, use the keyword override : if the function that you think overrides a virtual function of the base class has a different signature or doesn't even exist (e.g.typo...) the compiler will generate an error.

    Edit following your edit:

    I see that you've updated the code to make the overloaded non overriding functions virtual as well.

    Now the vtable of the derived function contains four distinct functions. However, through the base pointer you can only access the virtual functions defined in the base. This is why the MSVC debugger shows you only 2:

    enter image description here

    By the way, the debugger seems to always show the vtable as a member of the Base. But if you look at the assembler generated, you'll see the mangled names of all the virtual functions of the derived class in its vtable:

    enter image description here