Please see my example:
#include <iostream>
using namespace std;
class base {
public:
base() {}
~base() {}
virtual void funcBase() {
cout << "funcBase in class base" << endl;
}
};
class derived : public base {
public:
derived() {}
~derived() {}
virtual void funcBase() {
cout << "funcBase in class derived" << endl;
}
virtual void funcDerived() {} // I add virtual keyword to make sure funcDerived method is added in vtable of class
};
int main()
{
base* obj = new derived();
obj->funcBase(); // will print funcBase in class derived -> it's normal
obj->funcDerived(); // error: 'class base' has no member named 'funcDerived'
return 0;
}
So my question is, why can't I access the funcDerived method? I think the memory is of the derived class, so, the vpointer of class derived will point to vtable of it and this is ok!
Am I missing anything about the vtable and vpointer? What will be added to the vtable? Why is it restricted by pointer type?