Search code examples
c++typescompiler-constructionruntimedynamic-dispatch

Exactly why can compilers not determine a variable's true type until runtime?


I often hear about compilers not being able to determine the exact implementation of a method to use, under certain conditions. Fox example, we can imagine a scenario (so people say) where for a parent class with a method foo() that has been overridden in a child class, the compiler will not now which implementation of foo() to call until runtime. Hence we have the concepts of dynamic dispatch, vtables etc.

My question is, exactly why can the compiler not determine the exact implementation to call? I've stopped to think about it lately and I've been trying hard to justify it. Perhaps there is something really obvious I'm missing (I'll probably kick myself when I hear the answer). Is it just down to external circumstances? If so, how would that play out exactly?

Is this a language-dependent limitation or is there something more fundamental at hand?


Solution

  • Think about this:

    class Base
    {
    public:
        virtual void some_virtual_method(){...}
    };
    class Derived: public Base
    {
    public:    
        void some_virtual_method() override{...}
    };
    
    int choice;
    cin >> choice; // cannot know the value at compile time
    
    Base* foo;
    
    if(choice)
    {
        foo = new Base;
    }
    else
    {
        foo = new Derived;
    }
    
    foo->some_virtual_method();
    

    There is no way for the compiler to know which some_virtual_method() to invoke at compile time, as the choice solely depends on the user input. The dispatch is done via the function virtual table, and it is done at runtime.