Namespace Example
Here is an GameEngine
example:
Run it here.
This example demonstrates several important concepts related to namespace conflict resolution:
Same Function Names in Different Namespaces: Both
GraphicsLib
andMathLib
have functions nameddraw
andgetArea
, but with different parameters and implementations.Fully Qualified Names: We use fully qualified names to explicitly specify which namespace's function we want to call:
Global Namespace: We define a
draw
function in the global namespace and call it using the global namespace operator::
:Using Directives and Ambiguity: We demonstrate how using directives can lead to ambiguity:
Resolving Ambiguity: Even after using directives, we can still use fully qualified names to resolve ambiguity:
Overloading Across Namespaces: The
getArea
function has different parameters in each namespace, demonstrating how function overloading works across namespaces:Namespace Alias: We use a namespace alias to create a shorter name for
GraphicsLib
:
Key points about namespace conflict resolution:
Namespaces allow you to use the same function names in different contexts without conflicts.
Fully qualified names always provide unambiguous access to namespace members.
Using directives (
using namespace
) can lead to naming conflicts and should be used cautiously, especially in header files.Function overloading works across namespaces, allowing functions with the same name but different parameters.
Namespace aliases can provide shorter names for long namespace names, improving code readability.
Last updated