Search code examples
c++compile-timedynamic-binding

How can an object type be unknown at compile time?


I am currently learning about dynamic binding and virtual functions. This is from Accelerated C++, chapter 13:

[...] We want to make that decision at run time. That is, we want the system to run the right function based on the actual type of the objects passed to the function, which is known only at run time.

I don't understand the very idea that the type of an object can be unknown at compile time. Isn't it obvious from the source code?


Solution

  • Not at all. Consider this example:

    struct A {
      virtual void f() = 0;
    };
    
    struct B : A {
      virtual void f() { std::cerr << "In B::f()\n"; }
    };
    
    struct C : A {
      virtual void f() { std::cerr << "In C::f()\n"; }
    };
    
    static void f(A &a)
    {
      a.f(); // How do we know which function to call at compile time?
    }
    
    int main(int,char**)
    {
      B b;
      C c;
      f(b);
      f(c);
    }
    

    When the global function f is compiled, there is no way to know which function it should call. In fact, it will need to call different functions each time. The first time it is called with f(b), it will need to call B::f(), and the second time it is called with f(c) it will need to call C::f().