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

149 views Asked by At

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?

2

There are 2 answers

1
vsoftco On BEST ANSWER

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.

0
jamador On

The compiler doesn't have anything to do with runtime, except that it prepares the machine code that actually runs.

When an object is created dynamically and has polymorphic properties, and a function gets a parameter of the superclass type, the type is not known by the PROGRAM until it is passed in.