What’s the point of deleting default class constructor?

Consider the following class:

struct Foo {
    int i;
};

This class is an aggregate, and you can create an instance with all three of these definitions:

int main() {
    Foo f1;     // i uninitialized
    Foo f2{};   // i initialized to zero
    Foo f3{42}; // i initialized to 42
}

Now, let’s say that you don’t like uninitialized values and the undefined behaviour they could produce. You can delete the default constructor of Foo:

struct Foo {
    Foo() = delete;
    int i;
};

Foo is still an aggregate, but only the latter two definitions are valid — the first one is now a compile-time error.

Leave a Comment