Search code examples
c++inheritancec++17

Does C++ automatically downcast in order to find the right virtual function?


Question Polymorphism, Downcasting, and Virtual Functions seems vague and I'm not sure whether it's the same or a different question. One answer seems to answer my question (yes), but to make sure it's succinct. Here's my example.

class BaseClass {
public:
   virtual int myFunc() {
      return 0;
   }
};

class DerivedClass : BaseClass {
public:
   virtual int myFunc() {
      return 1;
   }
};

main() {
   DerivedClass* dclass = new DerivedClass;
   BaseClass* thinkImBaseClass = dclass;
   cout << "myFunc returns " <<  thinkImBaseClass->myFunc() << endl;
}

Does some runtime calculation discover that thinkImBaseClass is really DerivedClass? Or does the programmer have to cast it so the compiler knows at compile time:

((DerivedClass*)thinkImBaseClass)->myFunc();

Solution

  • Your program will do a vtable (virtual table) lookup at runtime to call the function from the derived class. It knows to do this because you declared the function as virtual in the base class.

    Objects of either class will contain a hidden vpointer, a pointer to a vtable for the class it was constructed as. The vtable contains a set of pointers to the actual virtual functions for the class.