Style” in programming refers to the choices one makes about formatting, naming, organization, and other aspects of the code that don’t affect its meaning or correctness but that play an important role for any person reading the code.

There are many stylistic choices one can make, and none are necessarily right or wrong. However, making consistent choices throughout one’s code that are also consistent with other people’s code will make your code much easier for you and for others to read. A style guide gives guidance on those choices that one can follow to achieve that consistency. In our class, we will follow Google’s C++ Style Guide.

It is quite long and detailed. Much of it only applies to aspects of C++ that we will not be using in our class. For us, the most important sections are:

  • Scoping, especially Local Variables
  • Naming, especially:
    1. Local and global variables will be named in lower_case_with_underscores.
    2. Class member variables (attributes) will be named with_a_trailing_underscore_.
    3. Class names will be named in capitalized CamelCase (wikipedia).
    4. Functions, including class methods, will be named in capitalized CamelCase.
    5. All names should be descriptive, other than loop counter variables like i.
  • Comments, especially:
    1. Variable, class, and function comments come before the commented component.
    2. No specific format is required for comments, but they should be descriptive and clearly explain how to use the function/class being commented.
    3. Prefer // over /* and */.
  • Formatting
    1. Horizontal whitespace: Use 1 space around (most) operators. E.g., x = y + z as opposed to x=y+z. Exceptions: ., ->, ++, and --. Put 1 space before every opening { curly brace. Do not put a space between a function name and its argument or parameter list. E.g., write Function(arg1, arg2), not Function (arg1, arg2).
    2. Vertical whitespace: Use 1 (or a few) blank lines between functions/classes etc., as well as between related sections of code within a function (sort of like paragraph breaks in writing).
    3. Indentation: Indent each nested block 2 spaces at a time. Do not use tabs in your code. You should set your editor to emit spaces when you hit the tab key. (Replit should do this automatically.)

Additionally, here are some style guidelines and conventions for writing classes:

  • Classes should be declared and implemented in their own files, which are named ClassName.h (declaration) and ClassName.cpp (implementation).
  • Class data members (attributes) should be private, unless they’re constants meant to be used outside the class.
  • All classes should have explicit constructors and destructors, even if they do nothing, for clarity.
  • Use this-> to access an object’s attributes and methods from within its methods — this immediately differentiates them from normal variables and functions.