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. A default constructor is a constructor that can be called with no arguments:
class Foo {
public:
Foo() : val(0) {}
int val;
};
Foo obj;
std::cout << obj.val << "\n"; // 0If a class declares no constructors, the compiler generates a default constructor that does nothing. Members of fundamental types are left uninitialised:
class Foo {
public:
int val;
};
Foo obj; // OK: val is uninitialised.Declaring any other constructor stops the compiler from generating the default constructor:
class Foo {
public:
Foo(int v) : val(v) {}
int val;
};
Foo a(1); // OK.
Foo b; // ERROR.A constructor where every parameter has a default argument is also a default constructor:
class Foo {
public:
Foo(int v = 0) : val(v) {}
int val;
};
Foo a; // val = 0
Foo b(1); // val = 1Warning
Do not write empty parentheses when calling the default constructor. This declares a function instead of creating an object:
Foo obj(); // Function named obj that returns a Foo.
A default constructor that does nothing can be requested explicitly with = default, even when other constructors are declared:
class Foo {
public:
Foo() = default;
Foo(int v) : val(v) {}
int val;
};
Foo a; // val is uninitialised.
Foo b(1); // val = 1Braces can be used to call the default constructor without declaring a function:
Foo obj{};
Dan