I am struggling to understand why the following code works.
class b {
public:
b() {}
virtual void foo(void) {
// code 1
}
};
class d1 : public b {
public:
d1() {}
virtual void foo(void) {
// code 2
}
};
class d2 : public b {
public:
d2() {}
virtual void foo(void) {
// code 3
}
};
int main() {
b* b1 = new d1();
b1->foo(); // code 2 executes
b1 = new d2();
b1->foo(); // code 3 executes
}
From what I have heard, this is runtime polymorphism. So how does the program determine at runtime which derived class b1
is pointing to? The most in-depth answer I have seen in any text is that "the program knows b1
points to the base class portion of d1
when it's referencing d1
". But how does it know this? I am assuming the program just keeps track of what derived type was most recently assigned to it. Is this true?