A constructor is a special member function that runs when an object is created. It has the same name as the class and no return type:

class Circle {
public:
  Circle(double r) : radius(r) {}
  double radius;
};

Creating an object by calling the constructor with direct-initialisation:

Circle c1(2.0);
std::cout#include <iostream> << c1.radius << "\n";  // 2

Creating an object by calling the constructor with copy-initialisation:

Circle c2 = Circle(3.0);
std::cout#include <iostream> << c2.radius << "\n";  // 3

Creating an object by calling the constructor with list-initialisation:

Circle c3{4.0};
std::cout#include <iostream> << c3.radius << "\n";  // 4

Constructors are used to put the object into a valid state before it is used:

class Circle {
public:
  Circle(double r) {
    radius = r;
    if (radius < 0) {
      radius = 0;
    }
  }
  double radius;
};

Multiple constructors can be defined if they have different parameter lists:

class Circle {
public:
  Circle() : radius(1.0), scale(1.0) {}
  Circle(double r) : radius(r), scale(1.0) {}
  Circle(double r, double s) : radius(r), scale(s) {}
  double radius;
  double scale;
};

Circle a;            // selects Circle().
Circle b(2.0);       // selects Circle(double).
Circle c(2.0, 2.0);  // selects Circle(double, double).

References