pasha
pasha

Reputation: 2115

Does C++ use static name resolution or dynamic name resolution?

I have been reading about "Name resolution" in wikipedia (Name resolution WIKI) and it has been given in that that C++ uses "Static Name Resolution". If that is true then I couldn't figure out how C++ manages to provide "polymorphism" without using dynamic name resolution.

Can anyone please answer whether C++ uses "Static Name Resolution" or "Dynamic Name Resolution". If it is static, can you also explain how C++ provides polymorphism.

Upvotes: 1

Views: 417

Answers (2)

Nicol Bolas
Nicol Bolas

Reputation: 473427

Wikipedia's definition of name resolution is about how tokens are resolved into the names of constructs (functions, typenames, etc). Given that definition, C++ is 100% static with its name resolution. Every token that represents an identifier must be associated at compile-time with a specific entity.

C++ polymorphism is effectively cheating. The compiler can see that a static name resolves to a member function defined with the virtual keyword. If the compiler sees that the object you are calling this on is a dynamic object (ie: a pointer/reference to that type rather than a value of that type), the the compiler emits special code to call that function.

This special code does not change the name it resolves to. What it changes is the function that eventually gets called. That is not dynamic naming; that is dynamic function dispatch. The name gets resolved at compile-time; the function gets resolved at runtime.

Upvotes: 7

Emeraude
Emeraude

Reputation: 9

C++ use static name resolution because it renames each function to made each one have an unique.
That mean that the function int foo(int bar) will be known by the compiler as something like _Z3fooi, while int foo(float bar) will be known as something like _Z3foof.
This is what we call name mangling.

Upvotes: 0

Related Questions