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?
What is the default constructor? Java doesn't require a constructor when we create a class. However, it's important to know what happens under the hood when no constructors are explicitly defined. The compiler automatically provides a public no-argument constructor for any class without constructors.
The default constructor of MyClass is used to initialize all the elements. When a derived class constructor does not explicitly call the base class constructor in its initializer list, the default constructor for the base class is called.
This default constructor supplied by Java as above calls the super class's no-arg constructor. If it can't find one, then it will throw an error.
If you don't define the default constructor, and someone later adds a constructor with parameters and forgets to also add the parameterless constructor, the default constructor will go away and that could break existing code.
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.
There are a few reasons to delete the default constructor.
= delete
is a style thing, as @HolyBlackCat said, but it does clarify your intent by telling the client code to only call the constructor with the parameters.If the second statement was unclear, consider the following example:
class A { public: //A() = delete; A(int, int) {}; };
If you tried to call the default constructor right now, you would get an error that would look something like (GCC 7.2):
error: no matching function for call to 'A::A()'
However, if you uncommented the line with the = delete
, then you would get the following:
error: use of deleted function 'A::A()'
This makes it explicitly clear that one is trying to use a deleted constructor in comparison to the other error, which is somewhat unclear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With