Skip to content

C++ Naming

// MyClass.h
#pragma once

#include <string_view>

namespace myProjectNamespace::MyProjectSubnamespace
{
class MyClass
{
public:
    // Single line comment.
    enum class MyEnum {
        firstEnumValue,
        secondEnumValue
    };

    /* This is a multi-line comment.
       It is useful to write a comment on multiple lines! */
    MyClass() = default;
    explicit MyClass(int singleParameter);
    MyClass(int firstParameter, std::string_view secondParameter);

    static constexpr int myConstant{5};
    static constexpr float myFloatConstant{1.0f};

    // myMember getter.
    int myMember() const;
    // myMember setter.
    void setMyMember(int myMember);
    // method that does something!
    void doSomething();

protected:
    // Usually empty (don't write the keyword if it's empty).

private:
    int m_myMember{0};
};
} // namespace myProjectNamespace::MyProjectSubnamespace

Source

// MyClass.cpp
// Class header <- Do not add this comment in real code
#include "MyClass.h"

// C system headers <- Do not add this comment in real code
#include "stdlib.h"

/* STL headers. <- Do not add this comment in real code
   All of these should be used in this file, but as it is a
   sample file, it is not the case. */
#include <algorithm>
#include <iostream>
#include <string_view>
#include <vector>

// Other libraries headers <- Do not add this comment in real code
#include <OtherWitekioProjectFile.h>
#include <nlohmann/json.hpp>

// Your project headers <- Do not add this comment in real code
#include "MyOtherClass.h"

namespace MyProjectNamespace::MyProjectSubnamespace
{

MyClass::MyClass(int singleParameter)
    : m_myMember(singleParameter)
{
}

MyClass::MyClass(int firstParameter, std::string_view secondParameter)
    : m_myMember(firstParameter)
{
    const std::size_t size{secondParameter.size()};
    m_myMember += size;
}

int MyClass::myMember() const
{
    return m_myMember;
}

void MyClass::setMyMember(int myMember)
{
    if(myMember != m_myMember) { // check is not necessary for basic types
        m_myMember = myMember;
    }
}

void MyClass::doSomething()
{
    // Nothing to do
    if(m_myMember == myConstant) {
        return;
    }

    MyOtherClass myOtherClass{};

    if(m_myMember < 0) {
        myOtherClass.doSomething();
        return;
    }

    switch(m_myMember) {
    case 0: {
        myOtherClass.doSomethingElse(0);
        break;
    }
    case 1:
    case 2:
    case 3: {
        myOtherClass.doSomethingElse(myConstant);
        break;
    }
    // TODO(AROSS): That's how you write a TODO!
    default:
        myOtherClass.doSomethingElse(m_myMember);
        break;
    }
}

} // namespace myProjectNamespace::MyProjectSubnamespace