why overriding is resolved at runtime whereas overloading is resolved at compile time ?
is there any reason that overriding cant be resolved at compile time.
why overriding is resolved at runtime whereas overloading is resolved at compile time ?
Share
Assuming you’re talking about polymorphism, i.e.
The above code allows something like this to work as expected:
It is important to realize that
CallFoo()knows nothing about whatbactually is (it could be referring to aBaseinstance or to aDerivedinstance). AllCallFoo()gets is a reference toBase, which tells nothing about what it actually refers to, so there’s no way a compiler can tell what it is when it compilesCallFoo(). Therefore, determining whetherBase::Foo()orDerived::Foo()should be called is necessarily a runtime decision.Removing the
virtualkeywords (to disable overriding) would cause the above code to print outBase::Foo()twice, notBase::Foo()thenDerived::Foo(). This is because without thevirtualkeyword the compiler would simply resolve the call toBase::Foo()at compile time.That being said, because virtual functions incur some overhead (after all, the right function that needs to be called is a runtime decision), compilers will try their best to figure out the actual type of
binCallFoo()if it can. In that case, it becomes a compile-time decision. It is, however, an implementation detail.