16.3. C++ code style usedΒΆ

/*
    Copyright/license boilerplate
*/


// In header (.h) files:
#pragma once

#define ANY_MASTER_SWITCHES_FOR_FILE

// In source (.cpp) files:
#include "myheader.h"

// Then:
#include <standard_library_file/in>
#include <zz_alphabetical/order>
#include <qt_libraries/in>
#include <zz_alphabetical/order>
#include "myproject/libraries/in"
#include "zz_alphabetical/order"

#ifdef SOME_MASTER_SWITCH
#include "conditional/include.h"
#endif

#define SOME_MACRO(x) x;  // but... really?

const QString SOME_CONSTANT;


namespace mynamespace {

// ... lower case so it's easy to distinguish Class::member from
//     namespace::member

// namespace contents NOT indented

}  // namespace mynamespace


class SomeClass {
    // Descriptive comments

    Q_OBJECT  // if applicable

public:
    // other classes and structs

public:
    SomeClass();
    // other constructors

    ~SomeClass();

    void someFunction();
    int& rFunctionReturningReference();

    // ...

protected:
    // functions

private:
    // functions

public:
    int public_member;  // e.g. for structs; no "m_"

private:
    int m_member_variable;  // perfectly clear

    static int s_static_variable;

    // NOT: int mMemberVariable;  // just because Stroustrup and Python habits
    // NOT: int memberVariable;  // helpful to have some indicator of membership
    // NOT: int member_;  // I hate this.

    char* pointer;  // space AFTER the *; see Stroustrup

};

// ============================================================================
// Big divider
// ============================================================================

void SomeClass::someFunction(int param)
{
    // Indents are 4 spaces.

    int stack_variable;
    if (param > 1) {
        braceEvenForSingleStatement();
    }
    if (very_long_condition_1 && very_long_condition_2 &&
            very_long_condition_3 && very_long_condition_4) {
        // we indent the subsequent parts of the "if" statement once more.
    }
}

// ----------------------------------------------------------------------------
// Small divider
// ----------------------------------------------------------------------------

Note other popular coding standards:

C++

Other languages