Multiple using Statements

Can I have multiple using statements for the same namespace in different scopes? What happens if I do?

Yes, you can have multiple using statements for the same namespace in different scopes. The using statement only applies to the scope in which it appears and any nested scopes.

If you have multiple using statements for the same namespace in different scopes, each one will apply only to its own scope and any nested scopes.

For example:

#include <iostream>

namespace MyNamespace {
  void Foo() {
    std::cout << "MyNamespace::Foo()\n";
  }
}

void Function1() {
  using MyNamespace::Foo;

  // Calls MyNamespace::Foo()
  Foo();
}

void Function2() {
  // No using statement here
  // Explicit namespace qualifier needed
  MyNamespace::Foo();
}

int main() {
  using MyNamespace::Foo;
  Foo();// Calls MyNamespace::Foo()
  Function1();
  Function2();
}
MyNamespace::Foo()
MyNamespace::Foo()
MyNamespace::Foo()

The using statement in Function1 applies only within that function, while the using statement in main applies to main and any functions called from main that don't have their own using statements.

Namespaces, Includes, and the Standard Library

A quick introduction to namespaces in C++, alongside the standard library and how we can access it

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Why Use Namespaces in C++?
What are the benefits of using namespaces in C++? When should I use them in my code?
Setting Include Paths
How do I set up my compiler to find header files in different directories?
Namespace Aliases
What is a namespace alias and when would I use one?
Header Include Order
Does the order of #include directives matter? If so, what's the correct order?
Explicit std:: Namespace
Why do you use explicit std:: namespace qualifiers in this lesson's code examples instead of 'using namespace std;'?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant