Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same function name in different namespaces

Tags:

c++

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()?

like image 918
White Philosophy Avatar asked Jul 21 '15 06:07

White Philosophy


2 Answers

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.

like image 168
Paolo M Avatar answered Sep 30 '22 21:09

Paolo M


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.

like image 23
Mahesh Attarde Avatar answered Sep 30 '22 21:09

Mahesh Attarde