What's the point of deleting default class constructor?

Derek Johnson picture Derek Johnson · Feb 7, 2018 · Viewed 8.8k times · Source

I'm preparing for my CPP exam and one of the question is: Can you delete default class constructor and if so, what would be the reason to do so? OK, so obviously you can do it:

class MyClass 
{ 
  public: 
    MyClass() = delete; 
};

but I do not understand why would you do it?

Answer

Quentin picture Quentin · Feb 7, 2018

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.