Search code examples
c++overridingvirtual-functionsvptr

Why is a vptr required when the derived class doesn't override the virtual function?


class base {
public:
    void virtual fn(int i) {
        cout << "base" << endl;
    }
};

class der : public base{
    public:
    void  fn(char i) {
        cout << "der" << endl;
    }
};

int main() {

    base* p = new der;
    char i = 5;
    p->fn(i);
    cout << sizeof(base);
    return 0;
}

Here signature of function fn defined in base class is different from signature of function fn() defined in der class though function name is same. Therefore, function defined in der class hides base class function fn(). So class der version of fn cannot be called by p->fn(i) call; It is fine.

My point is then why sizeof class base or der is 4 if there is no use of VTABLE pointer? What is requirement of VTABLE pointer here?


Solution

  • Note that this is highly implementation dependent & might vary for each compiler.

    The requirement for presence of vtable is that the Base class is meant for Inheritance and extension, and a class deriving from it might override the method.

    The two classes Base and Derived might reside in different Translation Unit and the compiler while compiling the Base class won't really know if the method will be overidden or not. So, if it finds the keyword virtual it generates the vtable.