Namespaces
Before diving into Inheritance, it’s helpful to understand namespaces, as you may encounter them in upcoming assignments. In C++, a namespace is a way to group multiple definitions—such as classes, functions, and variables—under a named umbrella. This approach helps you avoid naming conflicts and clearly distinguishes different pieces of code, even if they share the same identifier.
namespace name {
// All grouped definitions go here
} // namespace nameAccessing Items
Section titled “Accessing Items”Similar to how you’ve been using cout, endl, and other classes in your driver file, you have
three different ways to access the code you’ve written in a namespace:
- Qualified Name
For one time use cases like when you use std::cout inside of main:
csce240::ItemName x;- Using Individual Items
For multiple uses just like using std::cout:
using csce240::ItemName;ItemName x; // Direct use after the using declaration- Using Entire Namespace
When you want to import everything:
using namespace csce240;// Now everything under csce240 can be referenced directlyExample
Section titled “Example”This is an example of how your header file should look. Your header guards and import come before the namespace:
// Copyright 2024 CSCE240
#ifndef EXAMPLE_H_#define EXAMPLE_H_
#include <iostream>
using std::cout;using std::endl;
namespace csce240 {
class MyClass { // Definition}
} // namespace csce240
#endifYour source file is structured the same in that you import everything first, then you write your member implementation inside the namespace:
// Copyright 2024 CSCE240
#include <iostream>
using std::cout;using std::endl;
namespace csce240 {
// Implementation
} // namespace csce240
#endifGoogle Style
Section titled “Google Style”There are a couple of Google Style requirements when creating namespaces:
-
The names of a
namespaceshould be in lowercase letters and should follow snake_case notation. -
You should comment
namespaceand the name of yournamespaceafter the ending brace. Since an ending brace is code, you need to use at least two spaces between code and comment to adhere to the Google Style Guide for commenting in the same line as code (mentioned in the welcome page that introduced you to style requirements).