Constructors
A constructor is the member function that turns raw storage into a usable object by establishing the class invariant. It has the class's name, no return type, and runs exactly once per object, before the object's lifetime begins.
Detailed Explanation
The point of a constructor is not "setting the fields". It is making a promise. After a constructor returns normally, every statement the class claims about itself must be true: the cached total matches the tracks, the file handle is open, the pointer is either null or owns something valid. Every other member function may then assume that promise and only has to preserve it.
That is why an object with no constructor is a hazard. A struct Point { int x, y; }; declared as Point p; has indeterminate members, and reading one is undefined behavior. A constructor removes the possibility of an object that exists but means nothing.
Forms. A default constructor takes no arguments. A parameterized constructor takes the data the invariant needs. The compiler writes a default constructor for you only if you declare no constructor at all — declare any constructor, even a two-argument one, and the implicit default disappears. That is deliberate: if a class needs a name to be meaningful, Playlist p; should not compile.
Two explicit forms control that generation. = default asks the compiler for its version, which you use to get a default constructor back after declaring another one, or to keep a type trivially constructible. = delete removes a function entirely, and calling it is a compile error rather than a link error.
explicit matters more than it looks. A constructor callable with one argument doubles as an implicit conversion. Given class Buffer { Buffer(int size); };, the call takesBuffer(64) silently allocates a 64-element buffer, and buffer = 3 quietly replaces your data with a three-element one. Marking it explicit forces Buffer(64) at the call site and kills the accidental conversion. Default to explicit on any single-argument constructor and drop it only when the conversion is genuinely part of the design, as it is for std::string from a string literal.
Delegating constructors let one constructor call another in its member initializer list, so shared validation lives in one place instead of being copy-pasted across three overloads. The delegated-to constructor runs to completion first, then the delegating one's body.
A constructor cannot return a value, not even an error code, because there is no object yet to return it from. To signal failure you throw. If a constructor throws, the object never existed, its destructor is not called, and any members already constructed are destroyed in reverse order. This is why each resource belongs in its own RAII member: two raw handles acquired in one constructor body leak the first if the second throws. The alternative to throwing is a static factory function returning std::optional<T> or a result type, which suits cases where failure is expected rather than exceptional.
Order is fixed and not up to you. Base classes are constructed first, in the order they are listed. Then non-static data members, in declaration order — not the order in the initializer list. Then the constructor body runs. Constructors interact with the other special members through the rule of three, five, and zero, covered in cpp/memory/rule-of-three-five-zero.
Code Examples
#include <stdexcept>
#include <string>
#include <utility>
class Playlist {
public:
// Delegating: the one-argument form reuses the full constructor's checks.
explicit Playlist(std::string name) : Playlist(std::move(name), 500) {}
Playlist(std::string name, int capacity)
: name_(std::move(name)), capacity_(capacity) {
if (name_.empty()) throw std::invalid_argument("playlist needs a name");
if (capacity_ <= 0) throw std::invalid_argument("capacity must be positive");
// Invariant now holds: non-empty name, positive capacity.
}
Playlist() = delete; // a nameless playlist is meaningless, so forbid it
private:
std::string name_;
int capacity_;
};
int main() {
Playlist p("Focus"); // ok
// Playlist q; // compile error: default constructor deleted
// Playlist r = "Focus"; // compile error: constructor is explicit
}#include <iostream>
struct Base { Base() { std::cout << "base "; } };
struct Widget : Base {
struct Part {
explicit Part(const char* tag) { std::cout << tag << ' '; }
};
// Initializer list order is second, first — but declaration order wins.
Widget() : second_("second"), first_("first") { std::cout << "body\n"; }
Part first_;
Part second_;
};
int main() {
Widget w; // prints: base first second body
}Common Gotchas
Declaring one constructor deletes the implicit default one
adding `Playlist(std::string)` makes `Playlist p;` stop compiling, and makes the class unusable in containers that need default construction. Add `Playlist() = default;` back only if a default-constructed object can actually satisfy the invariant.
Do not call a virtual function from a constructor expecting an override
during base construction the derived part does not exist, so the call resolves to the base version. If the function is pure virtual, the behavior is undefined.
`Widget w();` declares a function
it looks like a default-constructed object but parses as a function declaration taking no arguments and returning `Widget`. Write `Widget w;` or `Widget w{};`.
Members initialize in declaration order, not list order
initializing one member from another that appears later in the class reads an object whose lifetime has not begun. Compile with `-Wreorder` and keep the two orders identical.