Some guidelines for C++ programming

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

bool operator==(const Position &other) {}

const member functions

Use const specifier for getters in user defined classes

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(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

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

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.

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

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store