Aller au contenu

Naming Conventions

Header and source files

  • In C++, the code can be split between a .cpp file (known as source file) and a .hpp file (known as header file). The constructors and methods are declared in the .hpp file but the actual implementations are listed in the .cpp file.
  • In the .cpp file, each constructor or method definition is preceded by the name of the class followed by :: (e.g. void LED::toggle()).

Here, the Point class is separated in the two corresponding files. The main.cpp file must then import the Point.h file to access the public methods and variables.

Point.hpp

#ifndef EMBEDDED_C__POINT_HPP
#define EMBEDDED_C__POINT_HPP

class Point {
public:
    // constructors
    Point();
    Point(float x, float y);

    // public methods
    void move(float dx, float dy);
    float x() const;
    float y() const;

private:
    // private data fields
    float _x;
    float _y;
};

#endif //EMBEDDED_C__POINT_HPP

Point.cpp

#include "point.hpp"

Point::Point() : _x(0), _y(0) {
}


Point::Point(float x, float y) : _x(x), _y(y) {
}

void Point::move(float dx, float dy) {
    _x += dx;
    _y += dy;
}

float Point::x() const {
    return _x;
}

float Point::y() const {
    return _y;
}

main.cpp

#include <iostream>
#include "point.hpp"

int main() {
    Point p1;
    std::cout << "(" << p1.x() << ", " << p1.y() << ")" << std::endl;
    Point p2(1, 2);
    p2.move(2, 3);
    std::cout << "(" << p2.x() << ", " << p2.y() << ")" << std::endl;
    return 0;
}

Namespaces

Namespaces are a way that helps to prevent name conflicts in different libraries or in large projects. All symbols defined within a namespace gets a name that prevents them from being mistaken for symbols with the same name defined within other scopes. Namespaces can be nested.

Purpose of Namespaces

  • Organize code into logical groups
  • Avoid naming conflicts
  • Make code more maintainable in large projects
  • Allow multiple definitions of the same identifier in different namespaces

Using Namespaces

You can define your own namespaces to organize your code:

namespace MyNamespace {
    class MyClass {
        // class definition
    };
}

And then use it:

MyNamespace::MyClass obj;

Or bring the namespace into scope:

using namespace MyNamespace;
MyClass obj;

Example

#include <iostream>

namespace A {
    class Example {
    public:
        void m() {
            std::cout << "m from namespace A" << std::endl;
        }
    };
}

namespace B {
    class Example {
    public:
        void m() {
            std::cout << "m from namespace B" << std::endl;
        }
    };
}

int main() {
    A::Example exampleA;
    B::Example exampleB;

    exampleA.m();
    exampleB.m();
    return 0;
}

Best Practices

  • Use meaningful names for your classes, functions, and variables
  • Follow consistent naming conventions in your project
  • Use namespaces to organize code logically
  • Prefer descriptive names over short abbreviations