C++ - Naming Conventions & Style
Overview
Estimated time: 25–40 minutes
Establish consistent naming and layout to improve readability and maintainability. This guidance is pragmatic and aligned with modern C++ practices.
Learning Objectives
- Adopt consistent naming for types, variables, functions, and constants.
- Organize code across headers and sources; use include guards or #pragma once.
- Use namespaces and avoid global using-directives in headers.
Prerequisites
Naming
- Types (classes/structs/enums):
PascalCase
(e.g.,Point3D
) - Functions/methods:
camelCase
(e.g.,computeArea
) - Variables:
snake_case
orcamelCase
(pick one; be consistent) - Constants:
kPascalCase
orALL_CAPS
(choose a standard) - Namespaces:
lowercase
(e.g.,graphics::render
)
Headers and sources
// point.h
#pragma once
struct Point { int x{0}; int y{0}; };
// point.cpp
#include "point.h"
Include order and self-contained headers
- Rule of thumb: your header includes what it uses; it should compile on its own.
- Prefer forward declarations in headers when possible; include in .cpp.
// foo.h (self-contained)
#pragma once
#include <string>
namespace app { struct Foo { std::string name; }; }
// foo.cpp
#include "foo.h" // first include your own header
#include <iostream>
Namespaces
namespace app { namespace util {
void log(const char* msg);
}} // namespace app::util
// Avoid: using namespace std; in headers.
Common Pitfalls
- Putting
using namespace std;
in headers—this pollutes the global namespace of all includers. - Omitting header guards or
#pragma once
, causing multiple definition errors.
Checks for Understanding
- Where should you avoid
using namespace
? - What are two common constant naming styles?
Show answers
- In headers; prefer fully qualified names or selective
using
in source files. kPascalCase
andALL_CAPS
.
Exercises
- Refactor a small snippet to adopt consistent naming across types, functions, and variables.
- Add
#pragma once
to your headers and verify a clean build with multiple includes.