bhylu.com

Advertisements

C++ Constructors

Initialize fields directly, validate a capacity and delegate a convenience constructor.

How it works

A constructor establishes an object’s initial state. Member initializer lists initialize fields before the body runs, avoiding a default construction followed by assignment. A delegating constructor reuses another constructor’s validation rather than duplicating a rule. explicit prevents certain unintended implicit conversions when a constructor could otherwise convert a single argument. If construction throws, the complete object never exists, while already-constructed member objects are cleaned up automatically.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror constructors.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · constructors.cpp

#include <iostream>
#include <stdexcept>

class RoundLoad {
    int capacity_;
public:
    RoundLoad() : RoundLoad(10) {}
    explicit RoundLoad(int capacity) : capacity_{capacity} {
        if (capacity <= 0 || capacity > 1000) { throw std::invalid_argument{"capacity"}; }
    }
    int capacity() const { return capacity_; }
};

int main() {
    RoundLoad standard;
    RoundLoad compact{4};
    std::cout << "Capacities: " << standard.capacity() << ' ' << compact.capacity() << '\n';
}

Expected result

Capacities: 10 4

The default constructor delegates to the same checked path as the explicit-capacity constructor. Initialization actually follows member declaration order, not the written order of an initializer list, which matters when one field depends on another. A constructor should not publish this to unrelated code before the invariant has been established.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.