Suppose I have different namespaces like apple namespace and orange namespace but both of the namespaces contain a function called myfunction().
What will happen when I call myfunction() in main()?
This is exactly what namespaces have been introduced for.
In your main()
, or in general in the global namespace, you will be able to select wich myfunctions
has to be called:
int main()
{
apple::myfunction(); // call the version into the apple namespace
orange::myfunction(); // call the orange one
myfunction(); // error: there is no using declaration / directive
}
In case of a using directive (using namespace apple
) or a using declaration (using apple::myfunction
), the last line of the main would have called the version inside the namespace apple
. If both versions of myfunction
were in scope, the last line would produce an error again, because in that case you would have to specify which function has to be called.
Consider following example.
namespace Gandalf{
namespace Frodo{
bool static hasMyPrecious(){ // _ZN7Gandalf5FrodoL13hasMyPreciousEv
return true;
}
};
bool static hasMyPrecious(){ // _ZN7GandalfL13hasMyPreciousEv
return true;
}
};
namespace Sauron{
bool static hasMyPrecious(){ // _ZN5SauronL13hasMyPreciousEv
return true;
}
};
bool hasMyPrecious(){ // _Z13hasMyPreciousv
return true;
}
int main()
{
if( Gandalf::Frodo::hasMyPrecious() || // _ZN7Gandalf5FrodoL13hasMyPreciousEv
Gandalf::hasMyPrecious() || // _ZN7GandalfL13hasMyPreciousEv
Sauron::hasMyPrecious() || // _ZN5SauronL13hasMyPreciousEv
hasMyPrecious()) // _Z13hasMyPreciousv
return 0;
return 1;
}
As per namespace in which function is declared, compiler generates unique identity of each function called Mangled Name which is nothing but encoding of namespace scope in which function is defined, function name, return type and actual parameters. see comments. As you create calls to this functions each function call looks for same mangled signature, if not found Compiler reports error.
Try Experimenting with clang -emit-llvm -S -c main.cpp -o main.ll if you are interested in internal working.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With