Namespaces, Includes, and the Standard Library

Multiple using Statements

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

Abstract art representing computer programming

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.

This Question is from the Lesson:

Namespaces, Includes, and the Standard Library

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

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Namespaces, Includes, and the Standard Library

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

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved