Converting constructors are single-argument constructors that implicitly convert a value of the parameter type to the class type:
class Circle {
public:
Circle(double r) : radius(r) {}
double radius;
};
Circle c = 2.0; // Same as Circle c(2.0);This implicit conversion also happens when passing an argument to a function:
void print(Circle c) {
std::cout#include <iostream> << c.radius << "\n";
}
print(2.0); // 2.0 is converted to a Circle.The implicit conversion can be disabled by marking the constructor with explicit:
class Circle {
public:
explicit Circle(double r) : radius(r) {}
double radius;
};
Circle a(2.0); // OK.
Circle b = 2.0; // ERROR.
print(2.0); // ERROR.
print(Circle(2.0)); // OK: conversion is written out.Note
Prefer marking single-argument constructors explicit unless the conversion is intended.
Multi-argument constructors can also be converting constructors through list-initialisation:
class Point {
public:
Point(int x, int y) : x(x), y(y) {}
int x;
int y;
};
void print(Point p) {}
Point p = {1, 2}; // OK.
print({1, 2}); // OK.The implicit conversion can be disabled by marking the constructor with explicit:
class Point {
public:
explicit Point(int x, int y) : x(x), y(y) {}
int x;
int y;
};
Point p = {1, 2}; // ERROR.
print({1, 2}); // ERROR.
Point q{1, 2}; // OK.
Dan