Some guidelines for C++ programming

Privalov Vladimir
2 min readAug 29, 2020

--

Here I will present my observations on style guidelines and best practices in C++.

const reference parameters for input values

Use const reference parameters for input values (for large objects like class instances) to avoid changing objects and unnecessary deep-copying

void addFile(const std::string& filename,
const std::set<std::string>& filePaths)
bool operator==(const Position &other) {}

const member functions

Use const specifier for getters in user defined classes

int x() const { return x_; }

This will guarantee that the method will not change the private class member because member functions marked const cannot change member variables or call non-const methods on them.

Default constructor for class

When you define constructor with parameters in class Animal compiler do not generate default constructor (source)

Position() noexcept : Position(0, 0) {}Position(const int x, const int y) : x_(x), y_(y) {}

explicit constructor

Is you define a class with a constructor taking single non-default parameter mark it by function specifier explicit

explicit Angle(const T value = 0) : value_(value) {}

This will cause following scenario to raise compilation error (source)

Angle a = 45;

When not using explicit keyword we define a converting constructor.

Illusion about returning non-const reference in getters

It’s a common practice in C++ to return references in getters.

std::vector<Vec2d> &points() { return points_; }

I was wondering why it is so popular. This looks like not a good practice as it’s unnecessary and it breaks incapsulation. Small observation of StackOverflow has revealed that this is useful for debugging purposes (see more on that here).

It’s recommended to specify getter as const

const std::vector<Vec2d> &points() const { return points_; }

That’s it. Good luck in programming on C++.

--

--

No responses yet