2.9 — Naming collisions and an introduction to namespaces

Let’s say you are driving to a friend’s house for the first time, and the address given to you is 245 Front Street in Mill City. Upon reaching Mill City, you pull up your map, only to discover that Mill City actually has two different Front Streets across town from each other! Which one would you go to? Unless there were some additional clue to help you decide (e.g. you remember his house is near the river) you’d have to call your friend and ask for more information. Because this would be confusing and inefficient (particularly for your mailman), in most countries, all street names and house addresses within a city are required to be unique.

Similarly, C++ requires that all identifiers be non-ambiguous. If two identical identifiers are introduced into the same program in a way that the compiler or linker can’t tell them apart, the compiler or linker will produce an error. This error is generally referred to as a naming collision (or naming conflict).

An example of a naming collision



When the compiler compiles this program, it will compile a.cpp and main.cpp independently, and each file will compile with no problems.

However, when the linker executes, it will link all the definitions in a.cpp and main.cpp together, and discover conflicting definitions for function myFcn. The linker will then abort with an error. Note that this error occurs even though myFcn is never called!

Most naming collisions occur in two cases:
1) Two (or more) definitions for a function (or global variable) are introduced into separate files that are compiled into the same program. This will result in a linker error, as shown above.
2) Two (or more) definitions for a function (or global variable) are introduced into the same file (often via an #include). This will result in a compiler error.

As programs get larger and use more identifiers, the odds of a naming collision being introduced increases significantly. The good news is that C++ provides plenty of mechanisms for avoiding naming collisions. Local scope, which keeps local variables defined inside functions from conflicting with each other, is one such mechanism. But local scope doesn’t work for functions names. So how do we keep function names from conflicting with each other?

What is a namespace?

Back to our address analogy for a moment, having two Front Streets was only problematic because those streets existed within the same city. On the other hand, if you had to deliver mail to two addresses, one at 209 Front Street in Mill City, and another address at 417 Front Street in Jonesville, there would be no confusion about where to go. Put another way, cities provide groupings that allow us to disambiguate addresses that might otherwise conflict with each other. Namespaces act like the cities do in this analogy.

A namespace is a region that allows you to declare names inside of it for the purpose of disambiguation. The namespace provides a scope (called namespace scope) to the names declared inside of it -- which simply means that any name declared inside the namespace won’t be mistaken for identical names in other scopes.

Key insight

A name declared in a namespace won’t be mistaken for an identical name declared in another scope.

Within a namespace, all names must be unique, otherwise a naming collision will result.

Namespaces are often used to group related identifiers in a large project to help ensure they don’t inadvertently collide with other identifiers. For example, if you put all your math functions in a namespace called math, then your math functions won’t collide with identically named functions outside the math namespace.

We’ll talk about how to create your own namespaces in a future lesson.

The global namespace

In C++, any name that is not defined inside a class, function, or a namespace is considered to be part of an implicitly defined namespace called the global namespace (sometimes also called the global scope).

In the example at the top of the lesson, functions main() and both versions of myFcn() are defined inside the global namespace. The naming collision encountered in the example happens because both versions of myFcn() end up inside the global namespace, which violates the rule that all names in the namespace must be unique.

The std namespace

When C++ was originally designed, all of the identifiers in the C++ standard library (including std::cin and std::cout) were available to be used without the std:: prefix (they were part of the global namespace). However, this meant that any identifier in the standard library could potentially conflict with any name you picked for your own identifiers (also defined in the global namespace). Code that was working might suddenly have a naming conflict when you #included a new file from the standard library. Or worse, programs that would compile under one version of C++ might not compile under a future version of C++, as new identifiers introduced into the standard library could have a naming conflict with already written code. So C++ moved all of the functionality in the standard library into a namespace named “std” (short for standard).

It turns out that std::cout‘s name isn’t really std::cout. It’s actually just cout, and std is the name of the namespace that identifier cout is part of. Because cout is defined in the std namespace, the name cout won’t conflict with any objects or functions named cout that we create in the global namespace.

Similarly, when accessing an identifier that is defined in a namespace (e.g. std::cout) , you need to tell the compiler that we’re looking for an identifier defined inside the namespace (std).

Key insight

When you use an identifier that is defined inside a namespace (such as the std namespace), you have to tell the compiler that the identifier lives inside the namespace.

There are a few different ways to do this.

Explicit namespace qualifier std::

The most straightforward way to tell the compiler that we want to use cout from the std namespace is by explicitly using the std:: prefix. For example:

The :: symbol is an operator called the scope resolution operator. The identifier to the left of the :: symbol identifies the namespace that the name to the right of the :: symbol is contained within. If no identifier to the left of the :: symbol is provided, the global namespace is assumed.

So when we say std::cout, we’re saying “the cout that lives in namespace std“.

This is the safest way to use cout, because there’s no ambiguity about which cout we’re referencing (the one in the std namespace).

Best practice

Use explicit namespace prefixes to access identifiers defined in a namespace.

Using namespace std (and why to avoid it)

Another way to access identifiers inside a namespace is to use a using directive statement. Here’s our original “Hello world” program with a using directive:

A using directive tells the compiler to check a specified namespace when trying to resolve an identifier that has no namespace prefix. So in the above example, when the compiler goes to determine what identifier cout is, it will check both locally (where it is undefined) and in the std namespace (where it will match to std::cout).

Many texts, tutorials, and even some compilers recommend or use a using directive at the top of the program. However, used in this way, this is a bad practice, and highly discouraged.

Consider the following program:

The above program doesn’t compile, because the compiler now can’t tell whether we want the cout function that we defined, or the cout that is defined inside the std namespace.

When using a using directive in this manner, any identifier we define may conflict with any identically named identifier in the std namespace. Even worse, while an identifier name may not conflict today, it may conflict with new identifiers added to the std namespace in future language revisions. This was the whole point of moving all of the identifiers in the standard library into the std namespace in the first place!


Avoid using directives (such as using namespace std;) at the top of your program. They violate the reason why namespaces were added in the first place.

We’ll talk more about using statements (and how to use them responsibly) in lesson 6.12 -- Using statements.

2.10 -- Introduction to the preprocessor
2.8 -- Programs with multiple code files

107 comments to 2.9 — Naming collisions and an introduction to namespaces

  • Anthony

    I'm writing some code C++ that uses the connect() function from sys/socket.h. I.e. this is a C function.

    I also have a class called Client which has a (different) connect() function as one of its member functions. The connect() function from sys/socket.h is called inside this member function.

    As a result, the compiler is throwing an error:

    because it thinks I'm referring to the member function. I have tried prefixing the call with

    , but then the compiler errors with:

    I don't really want to change the name of the member function since 'connect' is the best name for what it does. What else can I do?

  • I am very happy with the tutorial. But not to say what is best, but just put my opinion, I think the fact of not using "using namespace std;" not so convincing for the simple reason that C ++ (and other languages too) have reserved words, the programmer will hardly create a function named cout (especially him) that he knows very well that it is already a used word from the library. std from C ++.

    • min, max, function, string, byte, sort, map, array, begin
      Just to name a few that are more likely to appear elsewhere.
      `using namespace std;` is prone to cause name conflicts. Not necessarily conflicts for the compiler, but certainly for the reader.

    • Alex

      Nascardriver's answer is a good start. But even if you pick a name that works today, it may not work tomorrow. For example, you might name a function or a type string_view, figuring that to be a safe name. Then along comes C++17, with std::string_view being a new class in the standard library, and now you're at risk for having a naming conflict.

  • Keats

    Where is the path of namespace directory in Kali linux?, so I can see the contents of it

  • Samira Ferdi

    Hi, Alex and Nascardriver!

    The namespaces guaranteed the identifiers are unique? What if I use 2 libraries (and I have to use them) that have same namespace and identifiers?

  • nextlife

    I think you forgot to add #include <iostream> to the main.cpp for the example of naming collusion.

  • elFlaco

    At then end of section: "An example of a naming collision" you pose the question: "So how do we keep function names from conflicting with each other?" I'm not sure if I'm a little tired but is the answer to that question meant to be all the follow text on this page? Best,

  • The Maldives

    Ooooh thank god it's not short for "Sexually Transmitted Disease" :'-D

  • sri

    Does overriding a function contradict the ODR because you are redefining a unction with the same name and number of parameters?

    • Alex

      No, there's no conflict with the One Definition Rule (ODR). The ODR as applied to functions says there can only be one definition for a given function. Overloaded functions share a name, but are still considered unique functions. And because they're unique, each can have a different definition without violating ODR.

  • Samira Ferdi

    Many books that using "using namespace std" instead of "std::" for cout and cin. Is it best practice for "using namespace std" for cout and cin?

    • Kio


      Many books use it because it's easier to show code "snippets". Typing "using namespace std" is just referring (use namespaces from the standard library, hence std::).
      It's not best practice to use "using namespace std", why?

      Example if you are using two libraries:

      using namespace example;
      using namespace example1;

      and in both libraries, you have "cout", there will be conflict. Because compiler can't decide which to use!
      If you wrote it like this:

      example::cout or example1::cout, this will work because you have used "cout" from separate libraries.

      Still if you want to use "using namespace std",
      you can do it this way:

      using std::cout;
      using std::cin;

      and you can write a program like this:

    • Alex

      Kio nails it. This topic is discussed in more detail in lesson [link id="4979"].

  • Newbie Tony

    Thank you so much for   your contribution!!
    Alex when you die, you'll go directly to the heaven and sit with pope. XD

  • nick123

    how come I don't have to use 'namespace' in turbo C++ ?

    • Alex

      Because Turbo C++ is very old, and was created before they moved the standard library into the namespace. You really should use a more modern compiler if you can.

  • Tilkto Vigourr

    Alex  ,,,  you are my best friend.
    where u living bro ?

    Thank you so much for your great contribution !

  • Reeshabh

    According to what I have learnt, the modern compilers with 'non-.h' facility should work even without using std::cout, shouldn't it?

  • My dear c++ Teacher,
    Please accept my many thanks for your instructive answer (below, by July 7, 2017 at 12:19 pm).
    With regards and friendship.

  • My dear c++ Teacher,
    Please let me explain you that section 4.1a deals with naming confliction between variables. My question is about naming confliction between function and variable. My view is following:
    1. From 1st program follows that:
    1a. Compiler permits same name for function and variable inside its body.
    1b. When in function's body (in this case main()) there is function call before variable's definition, latter's name can be same as that of called function. My explanation is that called function, after its execution, is destroyed, so its name is available.
    2. From 2nd program it follows that when in function's body there is variable's definition before function's call, called function's name can NOT be same as variable's, apparently for variable is not yet destroyed so its name is not available inside hosting function.
    I my view correct?
    With regards and friendship.

    • Alex

      No. A variable name inside a block shadows an identical name from outside the block. So in the second program, the variable x shadows the function x. Therefore, when you try to call x(), the compiler notes that x is a variable, not a function, so calling it like a function doesn't make sense.

      In the top program, when the x function is called, the x variable hasn't shadowed it yet, so this is legal.

  • My dear c++ Teacher,
    Please let me say you following:
    This program

    works fine
    and this

    produces error
    line 13 error: 'x' cannot be used as a function

    I used Code::Blocks for both.
    Then I'm confused on when a function and a variable can have same name.
    With regards and friendship.

    • Alex

      The x declared inside the block shadows the x declared outside the block. See for more information.

  • kartik

    cout is reserved word right !
    but we should explicitly tell to the compiler that it is from std namespace
    does that mean we should create other identifiers namely cout cin but from other user-defined namespaces ?

    • Alex

      No, cout is the name of a predefined object. You should explicitly tell the compiler that it is from the std namespace.

      You can create your own namespaces if you wish, but I find this generally isn't necessary unless you're making a library that will be distributed to others.

  • Anshul

    Does this mean that all functions in standard library are declared inside namespace std?

    • Alex

      Yes. If you use a modern compiler and include the non-.h versions of the headers, all standard library functionality will be inside the std namespace.

      • Anshul

        What is "functionality" in this context? Function declarations or function definitions.

        I am confused. If all the standard library functionality is inside the namespace std which is the part of standard library then what other parts of standard library contain?

        • Alex

          By functionality, I mean the declarations and definitions for functions, objects (like std::cout), and types.

          Everything in the standard library is inside the std namespace. There are no other parts of the standard library outside of the namespace.

  • My dear c++ Teacher,
    Please let me say under example codes you state "Files a.cpp, b.cpp, and main.cpp will all compile just fine, since individually there’s no problem".
    I tried compile them individually by
    for a.cpp and b.cpp files it thrown error:
    "undefined reference to `main'"
    for main.cpp it thrown error:
    "undefined reference to `doSomething(int)'"
    With regards and friendship.

    • Alex

      They compile fine as files (as part of another program), but not as standalone programs, since (as you note) there's no main() function.

  • Luke

    The line after "Most naming collisions occur in two cases:" contains "an function" which, I think, is incorrect. It is not a big problem, I am just pointing it out :).

  • Alessan

    Hi Alex,

    Sorry but I also forgot to mention but if all the identifiers live in namespace std, then why must I include the iostream library aswell. Why not just use the namespace std.

    Thank you very much for the support. This website has helped me tremendously.

    • Alex

      Because the functionality you need is actually defined inside the iostream header (inside a namespace). To use it, you must first include the header (which makes the functionality of that header available for your use) and then tell the compiler how to get to it (inside the std namespace). Both steps are required.

      If you could just "use namespace std" and get to everything in the standard namespace, the implication is that you'd essentially be including the entire standard library, which would make your compilations a lot slower. It's better to pull in only what you need.

  • Alessan

    Hi Alex,
    Thanks for your previous reply. How does this piece of code work because surely the variable x is defined twice within the same function and also they share the same local scope. Also the output for "outer block y is re-assigned to 50 but surely local scope must disable this possibility.

    Thank you in advance

    • Alex

      They actually don't share the same scope. Inside the inner block, the name "x" refers to inner block x only. This is called shadowing. I talk about scoping and shadowing related topics in a lot more detail in lesson 4.1. Because there is no separate inner block y defined, while inside the inner block, y still refers to the y defined in the outer block.

  • Alessan

    Hi Alex,
    I have outlined function cout() ,in a separate file but still under the same project, as:

    Yet for some reason, I have an error stating ambiguity but I have clearly stated the 2 versions of cout (my function and one that lives in the c++ library). I used this example to gain a further understanding of namespaces.

    Please also note that I have realised the files are compiling and linking well with the expected outputs when I miss out

    • Alex

      The problem is this: You have a forward declaration "int cout()", telling the compiler that there is some function (somewhere) named cout. You're also getting a std::cout function from iostream. Because you're "using namespace std;", the compiler can't tell if the call to cout() is supposed to be to "int cout()" or "std::cout". I talk more about using statements in chapter 4. I general, I recommend avoiding them altogether.

  • Alex

    Hi Alex,
    Great tutorials by the way. Would it be useful to read through this topic and then topic 4.3b- Namespaces straight after since it may give me a better understanding of using and implement namespaces. Or shall I just follow the program and move on to the next module (Header Files). Thank you very much in advance.

    • Alex

      The tutorials should teach you everything you need to know in order, so there shouldn't be any problem if you wait until you encounter lesson 4.3b naturally. That said, if you're curious, there's no harm in reading 4.3b ahead of time, though you may encounter some other concepts that haven't been explained yet.

  • My dear c++ Teacher,
    Please let me report you a typo in first phrase, "gaven" instead of "given".
    With regards and friendship.

  • Yuan

    Do we have to add "std::" before those lines in the example? Why?

    • Alex

      You need to tell the compiler somehow that cout lives in the std namespace. The easiest way to do so is via the std:: prefix. There are other options, such as "using statements", which I cover in chapter 4, but I don't recommend them.

  • Alistair

    "Much like a city guarantees that all roads within the city have unique names"

    Nope, there are plenty of Queen's Roads in Bristol. I think you should consider a different analogy.


    • Alex

      Hmmm, but these Queen's Roads have different address ranges, right? Otherwise there would be no way to disambiguate them.

      • Alistair

        Address ranges?

        • Alex

          At least in the United States, each block has a range of addresses that all houses on that block fall between. For example, on the first block of the street, all houses might be numbered between 100 and 199, and on the second block, all the houses will be numbered 200 to 299.

          That way, even if the street is split into multiple segments (e.g. by a park or river in the middle) or are across town from each other, if you know the address range for a block, you can determine which segment of the street to go to. You'll never get two houses with the same number and street name, because the house numbering for different blocks should never overlap.

          • Alistair

            Blocks aren't a thing in the UK, no one planned anything with great concern until the Victorian era.

            No. They are completely different roads. The only way to disambiguate them is to know where they are. They may be on other sides of the city and each start from one.

  • My dear Teacher,
    please let me say that I understand "An example of a naming collision" as follows:

    Output is:
    I beg your comments.
    With regards and friendship.

  • Big"B"LuvRRR

    Regarding naming collisions or naming conflicts: couldn't we just create names that are practically guaranteed not to ever collide or conflicts, just adding an extra "xy0" to the end of every function we make???

    Surely there can be no problem with a "coutxy0()" or "cinz()" or anything similarly named!  I plan on using a global namespace directive at the outset and not worrying about collisions afterwards by just creating very unique though simple function names.  What could possibly go wrong with such an approach, please?

    • Alex

      You could, but doing so makes your code harder to read and remember how to use (e.g. was the function named coutxy0() or coutx0() or coutxy1() or what?).

  • Jim

    The statement below is real confusing and maybe even misleading. Aren't there other containers in the standard library besides (std namespace)? So, std namesspace is just one(or maybe part of one)of these containers isn't it?

    "Everything in the standard library lives inside a special container (called a namespace) that is named std (short for standard)."

    • Alex

      Not that I'm aware of. Everything in the standard library lives inside the std namespace.

      Perhaps there's a better word to use than "container". Maybe "area"?

      • Jim

        Thanks Alex,  But it's a bit hard for me to get my mind around exactly what namespaces are,  could you give us a better description ?

        This is kind of dumb but I'm sure others have wondered about this. I've got another question about std :: cin >> x;.  I know this put the user input value of x into memory. But can you put any thing else on that same line of code besides a comment?

        • Alex

          It's hard to describe namespaces right now because we haven't covered some of the language that I really need to describe them accurately. A way to think of them for now: Namespaces apply a prefix to variable and type names. This prefix functions much like your last name in real life does -- it helps ensure that even though you may have the same first name as someone else, you can still be uniquely identified by using both your names together. Does that make sense? I talk more about namespaces in chapter 4.

          As for your second question, because this statement ends in a semicolon, you could put another statement to the right of that statement. However, that's generally considered bad form. One statement per line is the recommended practice, with an optional comment to the right (or above).

Leave a Comment

Put all code inside code tags: [code]your code here[/code]