C++ Reference ยท Types and Language Concepts
Constructors in C++
Reference for C++ constructors: default, parameterized, delegating, converting and explicit constructors, member initializer lists, initialization order and inherited constructors.
A constructor is a special member function that runs when an object of its class is created. It has the same name as the class, no return type, and its job is to put the object into a valid state. A class can have many constructors that differ in their parameters; overload resolution picks one at each creation site.
Members and base classes are initialized before the constructor body runs, using the member initializer list (: a(1), b(2)). Anything you assign inside the body is a second step on an already-constructed member. For constants, references and members without default constructors, the initializer list is the only way.
class Account { std::string owner_; long cents_; public: Account(std::string owner, long cents) : owner_(std::move(owner)), cents_(cents) {} };
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Syntax
ClassName(params) : member1(init1), member2{init2}, Base(args) { body } ClassName() = default; // compiler-generated default constructor ClassName(const ClassName&); // copy constructor ClassName(ClassName&&) noexcept; // move constructor explicit ClassName(int); // not usable for implicit conversion ClassName(int x) : ClassName(x, 0) {} // delegating using Base::Base; // inheriting constructors
| Kind | Description |
|---|---|
| Default | Callable with no arguments. Generated automatically only if you declare no constructor at all. |
| Parameterized | Takes arguments. If it has one non-explicit parameter, it is also a converting constructor. |
| Copy / move | Build from another object of the same class. See Rule of three, five and zero. |
| Delegating | Calls another constructor of the same class in its initializer list; then it may not initialize members itself. |
| Inherited | using Base::Base; makes the base's constructors available; new members get default member initializers. |
Returns: nothing; the constructor initializes the object being created. A constructor cannot be virtual, static or const.
Errors / undefined behavior: an exception escaping a constructor means the object never existed (its destructor is not called, but already-built members and bases are destroyed). Calling a virtual function from a constructor dispatches to the version in the class being constructed, not to a derived override.
Usage notes
- Initialization order follows the order of declaration in the class, not the order in the initializer list. Bases first, then members. GCC warns with
-Wreorder. - Use the initializer list.
name_(std::move(name))constructs once; assigning in the body default-constructs and then assigns. It is mandatory forconstmembers, references and types without a default constructor. - Mark single-argument constructors
explicitunless you really want implicit conversion (likestd::stringfromconst char*). Without it, accidental conversions compile silently. - Default constructor traps. Declaring any other constructor removes the implicit default one; restore it with
= default. WritingT x();declares a function (the most vexing parse); useT x;orT x{};. - Default member initializers (
int count = 0;) apply to every constructor that does not initialize that member and reduce repetition. - Delegating avoids duplicating validation: put the real logic in one constructor, let the others forward to it.
- Throwing from constructors is the standard way to report failure; RAII members keep this exception-safe.
- Aggregates (no user-declared constructors, all public members) are initialized member by member with braces; see Brace initialization.
constexprconstructors let a class be used in constant expressions; they are implicitly allowed for literal types.explicit(bool)(C++20) makes explicitness conditional, mostly for templates.