Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

No naming conflict from two functions in global namespace (C++)?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading