Here’s a “recipe” for consistent, readable C++ naming—think of it as your go-to style guide you can bake into every project! 🍰
1. Decide on a Style Family
You’ll see two prevalent families in C++ land:
- PascalCase + camelCase
• Classes, structs, enums → PascalCase (e.g. ImageProcessor)
• Functions, variables → camelCase (e.g. loadImage(), pixelCount)
- snake_case
• Everything → snake_case (e.g. image_processor, load_image())
Pick one and stick with it throughout your codebase.
2. Class & Type Names
- Use PascalCase (UpperCamelCase).
- Make it a noun or noun phrase.
- Avoid abbreviations unless they’re universally known (e.g.
XMLParser, not XmLp).
Example:
cpp
class AudioFilter {
// …
};
struct Point3D {
double x, y, z;
};
enum ColorSpace { RGB, CMYK, HSV };
3. Function & Method Names
- Use camelCase (lowerCamelCase) or snake_case, per your chosen family.
- Start with a verb (describes action):
calculate, get, set, is, has, load, save.
- Keep them concise but descriptive.
Example (camelCase style):
cpp
// Member
void processImage(const Image& input);
// Free function
std::vector<Face> detectFaces(const Image& image);
Example (snake_case style):
cpp
void process_image(const Image& input);
std::vector<Face> detect_faces(const Image& image);
4. Parameters & Local Variables
- Often camelCase (if matching functions) or snake_case.
- Name them meaningfully:
- Bad:
int x, int y;
- Good:
int width, int height;
5. Member Variables
Common idioms to distinguish members from locals:
- Trailing underscore:
int count_;
- m_ prefix:
int m_count;
Pick one style:
cpp
class Foo {
int capacity_; // trailing underscore
std::string name_;
public:
void setCapacity(int capacity) { capacity_ = capacity; }
};
6. Constants & Macros
- Constants:
k prefix + PascalCase: static const int kMaxRetries = 5;
- Macros: ALL_CAPS:
#define MAX_BUFFER 1024
7. Abbreviations & Acronyms
- Treat acronyms as words:
XmlDocument (not XMLDocument)
parseHttpResponse() (not parseHTTPResponse())
8. Consistency Checks
- Automate with linters (clang-tidy, cpplint).
- Document your rules in a STYLE.md.
- Code-review for naming consistency.
Summary Checklist
With these ingredients, your code will be uniform, self-describing, and pleasant to read! 🚀🎂