What's the point of deleting default class constructor?

后端 未结 4 2179
轻奢々
轻奢々 2021-02-01 01:26

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:

4条回答
  •  遇见更好的自我
    2021-02-01 01:29

    There are a few reasons to delete the default constructor.

    1. The class is purely static, and you don't want users instantiating a class with only static methods/members. An example of such a class might be one that implements the factory design pattern using only static methods to create new classes.
    2. It wouldn't make sense for the class to have a default constructor (Since it requires parameters/There are no default values that would make sense for the class). In this case, the = 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.
    3. You do not want uninitialized data for an aggregate class.

    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.

提交回复
热议问题