0

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?

brickbobed
  • 169
  • 1
  • 10
  • 1
    It uses a "hidden" vptr at the beginning of each object, point to a vtable. Details: https://www.learncpp.com/cpp-tutorial/the-virtual-table/ – m88 Mar 04 '21 at 23:26
  • Well, to be fair, that is just *one* way it can be (and usually is) implemented. But the C++ standard has no concept of vtables, or really of how polymorphic dispatch is implemented at all. This is purely an implementation detail of the compiler, and there are [other possible implementations](https://stackoverflow.com/questions/4352032/) while still satisfying the behaviors outlined in the standard. – Remy Lebeau Mar 05 '21 at 01:43

0 Answers0