c++virtual-functionsvtabledynamic-dispatchvptr

does pointer "this" in c++ support virtual mechanism?


Consider that:

class B {
    void f() { vf(); };
    virtual void vf();
};

class D: public B{
    virtual void vf();
};

I thought that in C++ the implementation of B::f() is something like that:

f(B *this) {
    *(this->vptr[index])(this);
}

Is D::vf() called through the virtual mechanism in the following example?

B *p = new D();
p->f(); 

Solution

  • Answer is yes for the given example, but not for calls from a constructor of the base class, which executes before the derived class gets constructed.

    With a slightly modifed example:

    #include <iostream>
    
    class B {
    public:
        B() { f(); }
    
        void f() { vf(); };
        virtual void vf()  { std::cout << "B::vf" << std::endl; }
    };
    
    class D: public B{
        void vf() override { std::cout << "D::vf" << std::endl; }
    };
    
    int main()
    {
        B *p = new D();  // calls D::D() --> B::B() --> B::f() --> B::vf()
        p->f();          // calls B::f() --> D:vf()
    }
    

    The output is:

    B::vf
    D::vf