Consider the following code:
#include <cstdio>
struct Base {
void callNormalFn() {
normalFn();
}
void callVirtualFn() {
virtualFn();
}
void normalFn() {
printf("Base::normalFn\n");
}
virtual void virtualFn() {
printf("Base::virtualFn\n");
}
};
struct Derived : Base {
void callNormalFn() {
Base::callNormalFn();
}
void callVirtualFn() {
Base::callVirtualFn();
}
void normalFn() {
printf("Derived::normalFn\n");
}
virtual void virtualFn() {
printf("Derived::virtualFn\n");
}
};
int main() {
Derived d = {};
d.callVirtualFn();
//=> Derived::virtualFn (why?)
d.callNormalFn();
//=> Base::normalFn (why?)
}
From c++ virtual function call without pointer or reference, my understanding says that:
- there is an implicit
this
pointer insideBase::callVirtualFn()
orBase::callNormalFn()
, e.g.this->virtualFn()
- the
this
pointer should point to the current object being operated on (in this case, theDerived
class)
Why is then the this
pointer resolves to different classes when calling normal vs virtual functions?