'`this` pointer reference to normal vs virtual functions in superclass
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
thispointer insideBase::callVirtualFn()orBase::callNormalFn(), e.g.this->virtualFn() - the
thispointer should point to the current object being operated on (in this case, theDerivedclass)
Why is then the this pointer resolves to different classes when calling normal vs virtual functions?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
