Do you know how virtual functions works? Let’s try to re-implement them.
source: https://pixnio.com/nature-landscapes/snow/frost-winter-nature-snow-ice-crystal-snowflake-sphere-sky [CC0 license]]

In the following snipped, witch one of Mother::subFunction() or Child::subFunction() is called?

class Mother {
public:
    void mainFunction() {
        subFunction();
    }
    void subFunction();
};

class Child: public Mother {
public:
    void subFunction();
};

void use() {
    Child c;
    c.mainFunction();
}
It's Child::subFunction().

use():
        sub     rsp, 24
        mov     QWORD PTR [rsp+8], OFFSET FLAT:_ZTV5Child+16
        lea     rdi, [rsp+8]
        call    Child::subFunction()
        add     rsp, 24
        ret
I invite you to test it on compiler explorer.

If what you see in the assembly isn’t the function you were expected, it’s probably because you don’t understand yet what a virtual function is. The call to c.mainFunction(), is resolved to Mother::mainFunction(). When executing this function, a call to subFunction() is made. It will in its turn be resolved to the only function with the right signature, while being visible in Mother, witch is Mother::subFunction(). Indeed, Child::subFunction isn’t visible in Mother. If you want to be able to call Child::subFunction() from Mother when the real type of this is Child*, you need to be able to access it, and it will be done by making it a virtual function.


If you want to understand how virtual functions works, you need to replicate it with function pointer. For that, you need to create a function pointer in Mother, than will points to Mother::subFunction() if the dynamic type of the instance you are manipulating is Mother, and Child::subFunction() if it’s a Child. You could write a minimal example like this.


Unfortunately, the this pointer, isn’t passed as implicit argument to subFunction(), witch means that we can’t use member function. To fix this, the real solution is a bit more complicated.

Creative Commons License