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?
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.