Home > Mobile >  No naming conflict from two functions in global namespace (C )?
No naming conflict from two functions in global namespace (C )?

Time:11-30

I created two files, Linkage.cpp and External.cpp.

Linkage.cpp:

#include <iostream>

void Log(int x = 5)
{
    std::cout << x << "\n";
}

int main()
{
    Log();
    return 0;
}

External.cpp:

#include <iostream>

void Log(const char* message)
{
    std::cout << message << "\n";
}

Why am I not getting a linker error? Both these functions are defined in the global namespace, so there should be naming conflicts as with variables.

CodePudding user response:

Why am I not getting a linker error?

When you wrote

void Log(int x = 5)//this means that the function named Log can be called without passing 
                  //any argument because you have provided a default argument which will be 
                 //used in case you don't provide/pass any argument
{
   //..other code here
{

The above means that the function named Log can be called without passing any argument because you have provided a default argument which will be used in case you don't provide/pass any argument.

Next when you wrote

void Log(const char* message)//this means that this versoin of the function named Log will be called only if you pass an argument of type `char*` . 
{
    std::cout << message << "\n";
}

The above means that this verion of the function named Log will be called only if you pass an argument of type char* .

Now when your wrote:

 Log();

The first version which has a default argument will be used because you haven't provided any argument and so the first version can be used(since it is viable) and because the second version which must take an argument is not viable.

CodePudding user response:

Okay, I experimented around after @Retire Ninja pointed this out to me.

First, comment out all the code from External.cpp. Now, declare another Log function inside Linkage.cpp so that there are two functions inside this file that have the same name(Log) but different parameters. You will realise that using depending upon what arguments you supply, these Log functions will behave like different functions.

So, unlike variables, where same name means same variable in a namespace, functions need to have matching signatures too.

  • Related