Namespaces, Includes, and the Standard Library

Explicit std:: Namespace

Why do you use explicit std:: namespace qualifiers in this lesson's code examples instead of 'using namespace std;'?

Abstract art representing computer programming

In this lesson, I use explicit std:: namespace qualifiers for types and objects from the C++ Standard Library, like std::cout and std::string, instead of a using namespace std; statement. There are a few reasons for this:

  1. It makes it clear that these types and objects are from the Standard Library and not from the current project or some other library.
  2. It avoids potential naming conflicts. If your code defines a function or variable with the same name as something in the std namespace, and you have a using namespace std; statement, you'll get a naming conflict. Using explicit std:: avoids this.
  3. It's considered good practice in many codebases and style guides. While using namespace std; can be convenient for small examples or personal projects, it's often discouraged in larger codebases or when writing libraries.

For example, instead of:

#include <iostream>
using namespace std;

int main() {
  string message = "Hello, world!";
  cout << message << endl;
}

I would write:

#include <iostream>

int main() {
  std::string message = "Hello, world!";
  std::cout << message << std::endl;
}

The explicit std:: makes it clear where string, cout, and endl are coming from.

There are situations where a using statement can be appropriate, like within a limited scope such as a function, but for clarity and to promote good habits, I generally avoid using namespace std; in examples.

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:

  • 124 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