Search code examples
oopprogramming-languagesstatic-analysisvirtual-functions

Why is statically resolving virtual method calls so difficult?


Suppose we have the following pseudo code. I am talking about OO languages.

class A{

    foo(){...}

}

class B extends A{

    foo(){...}

}

class C extends B{

    foo(){...}
}

static void f(A a)
{

    A a=new A();
    a=new B();
    a.foo();

}

It's easy for us to recognize that a.foo() is calling function foo overridden in class B. So why it's hard for compilers to get this truth by static analysis? The fundamental question here is why statically determine the type of A is hard for a compiler?


Solution

  • The example you posted is extremely simplistic and does not show anything that requires a virtual method call. With your same classes, examine this function;

    void bar(A* a) {
      a->foo();
    }
    

    There is no way the compiler can tell at compile-time if a is an instance of B, or C, or a plain A. That can only be decided at runtime in the general case.

    The compiler can't even know if there will be new classes derived from A at some future point that will be linked with this code.