Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 171 ยท Object-Oriented Programming

Constructors and Member Initializer Lists

Master C++ constructors - default and parameterized constructors, member initializer lists and their order, default member initializers, delegating constructors, explicit and = default.

A constructor is a special member function that runs automatically when an object is created. Its job is to turn raw memory into a valid object: give every member a sensible value, check the arguments, and establish the class's invariants. Once a constructor finishes, the object should be ready to use, with no separate init() call to forget.

C++ constructors are more precise than in most languages, and that precision has rules you need to know. In this lesson you'll write default and parameterized constructors, learn why the member initializer list is the right place to initialize members (and why its order is decided by something else entirely), use default member initializers and delegating constructors to avoid repetition, stop accidental conversions with explicit, and ask the compiler for constructors with = default. You should know the basics from Classes and Objects.

Your first constructors

A constructor has the same name as the class and no return type, not even void. A class can have several constructors with different parameters (they are overloads, see Function Overloading). The one that takes no arguments is the default constructor.

C++ Default and parameterized constructors

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.

The invalid time never becomes an object: the constructor throws before it finishes, so there is no half-built Time lying around. That is the standard C++ way for a constructor to report failure (Exceptions). If exceptions aren't an option in your project, the usual alternative is a factory function returning std::optional<Time> or std::expected (Error Handling Without Exceptions).

Prefer braces {} when creating objects. They work everywhere, they reject narrowing conversions like Time{9.7, 30}, and Time t{}; can't be mistaken for a function declaration the way Time t(); can.

The member initializer list

The part between the : and the constructor body is the member initializer list:

C++
Time(int hours, int minutes) : hours_{hours}, minutes_{minutes} { /* body */ }

It is not a stylistic alternative to assigning in the body. Members are initialized before the body runs. If you don't mention a member in the list, it is initialized from its default member initializer, or default-constructed (or, for an int without a default, left uninitialized). Assigning in the body then overwrites a value that already exists.

For ints the difference is small. For members that are expensive to construct it means double work, and for some members it's the only option:

  • const members can't be assigned, only initialized.
  • Reference members must be bound when they are created.
  • Members without a default constructor must receive their arguments in the list.
  • Base classes are initialized there too (Inheritance).
C++ Initialization vs assignment in the body

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.

AssignsInBody builds its member twice (once empty, then assigned), while UsesInitList builds it once, directly from the argument. Make the initializer list your default and keep the constructor body for work that can't be expressed as initialization, like validation or logging.

Reference and const data members make a class impossible to assign with =, because the compiler can't re-seat a reference or overwrite a const. They're fine in classes that are never reassigned, but in most classes a pointer (or std::reference_wrapper) and a non-const member are more practical. The Rule of Zero, Three and Five returns to this.

Initialization order: declaration order wins

Here is the rule that surprises everyone once: members are initialized in the order they are declared in the class, not in the order you write them in the initializer list. If one member's initializer uses another member, the order of declarations decides whether that member already has a value.

GCC warns about a mismatched list with -Wreorder (part of -Wall). This example compiles with that warning on purpose and contains a real bug.

C++ Members initialize in declaration order

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.

The compiler reports 'Square::side_' will be initialized after 'int Square::area_' and also notices that side_ is used uninitialized. The broken area may print as 0 or as any other number. Two habits avoid this whole class of bug: write the initializer list in declaration order, and compute members from constructor parameters rather than from other members.

Default member initializers

A default member initializer (written where the member is declared, like int hours_ = 0;) gives a value that every constructor uses unless that constructor's initializer list says otherwise. It removes repetition when a class has several constructors, and it guarantees no member is ever forgotten.

C++
class Connection {
public:
    Connection() = default;                              // uses all the defaults below
    explicit Connection(std::string host) : host_{std::move(host)} {}   // port_ etc. stay default
    Connection(std::string host, int port) : host_{std::move(host)}, port_{port} {}

private:
    std::string host_ = "localhost";
    int port_ = 5432;
    int timeout_seconds_ = 30;
    bool use_tls_ = true;
};

Use default member initializers for every member that has a natural default, and the initializer list for values that come from arguments. With this style, a class can't end up with an uninitialized int.

Delegating constructors

When constructors share real logic (validation, normalization), one constructor can delegate to another by naming it in its initializer list. The target constructor runs completely first, then the delegating constructor's body.

C++ Delegating constructors share validation

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.

A delegating constructor's initializer list must contain only the delegation; you can't also initialize members there. For simple cases, default arguments (Fraction(long long n = 0, long long d = 1)) do the same job with one constructor, but delegation is clearer when the overloads take different types.

explicit: no surprise conversions

A constructor that can be called with one argument doubles as an implicit conversion. If Fraction has a Fraction(long long) constructor, then any function taking a Fraction silently accepts a plain integer. Sometimes that is exactly right (an integer is a fraction). Often it's a bug waiting to happen.

C++ explicit blocks accidental conversions

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.

Uncomment any of the three lines to see the errors, then remove explicit and watch them compile (into the bugs the comments describe). The rule of thumb used by most style guides: mark every single-argument constructor explicit unless the implicit conversion is natural and lossless, like std::string from a string literal. Since C++20 you can also write explicit(condition) with a compile-time condition, which generic library code uses.

= default, = delete and the implicit default constructor

If a class declares no constructors at all, the compiler writes a default constructor for you. It initializes members using their default member initializers and default-constructs the rest. As soon as you declare any constructor, that automatic default constructor disappears. If you still want one, ask for it with = default:

C++
class Settings {
public:
    Settings() = default;                    // the compiler-generated version, explicitly
    explicit Settings(std::string profile) : profile_{std::move(profile)} {}
private:
    std::string profile_ = "standard";
    int volume_ = 70;
};

= default is better than an empty body Settings() {}: it keeps the class trivial when possible and documents intent. The opposite, = delete, forbids a function. A common use is deleting a constructor overload you don't want to match, such as Meters(int) = delete; to reject integers. The Rule of Zero, Three and Five applies both to copy and move operations.

Braces prefer std::initializer_list constructors. For classes that have one, like std::vector, {} and () can mean different things: std::vector<int> a(3, 5); holds three fives, but std::vector<int> b{3, 5}; holds the two values 3 and 5. Use parentheses when you mean "size and value" arguments for containers; use braces everywhere else.

C++ Braces vs parentheses with initializer_list

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.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A class declares int area_; before int side_;, and its constructor is Square(int s) : side_{s}, area_{side_ * side_} {}. What happens?

    Members are initialized in declaration order, regardless of the list's order. area_ comes first and reads side_ before it has a value. GCC warns with -Wreorder.
  2. 2. Which member can ONLY be given its value in the member initializer list (or a default member initializer), not by assignment in the constructor body?

    A const member can't be assigned after it is created, so it must be initialized. The same goes for reference members and members without a default constructor.
  3. 3. A class has a single constructor Buffer(std::size_t size) without explicit. What does send(64); do for void send(const Buffer&)?

    A non-explicit single-argument constructor acts as an implicit conversion, so 64 becomes Buffer{64}. Marking the constructor explicit makes this line an error.
  4. 4. A class declares only Settings(std::string profile). What does Settings s; do?

    The compiler only generates a default constructor when you declare no constructors. Add Settings() = default; to get it back.
  5. 5. What does std::vector<int> v{4}; contain?

    Braces prefer the initializer_list constructor, so {4} is a list with one element. std::vector<int> v(4); creates four zeros.

Summary

  • A constructor has the class's name and no return type. It runs when the object is created and should leave it fully valid, throwing if the arguments are invalid.
  • Members are initialized before the constructor body runs. Use the member initializer list; it's required for const members, references, members without default constructors and base classes.
  • Members are initialized in declaration order, not list order. Keep both orders the same and compute from parameters, not other members.
  • Default member initializers give every constructor a fallback value and prevent uninitialized members.
  • A delegating constructor calls another constructor of the same class to share logic.
  • Mark single-argument constructors explicit unless the implicit conversion is natural.
  • Declaring any constructor removes the implicit default constructor; restore it with = default. = delete forbids an overload.
  • Prefer brace initialization, except for container size/value arguments, where braces pick the initializer_list constructor.

Next: Destructors and RAII, where you'll see what happens at the other end of an object's life.