The default constructor, which is a constructor that has no parameters, is a way to make you out of nothing in the C + + language. Constructors can initialize objects, and the default constructor can initialize objects without taking advantage of any external data that is created on the object. Sometimes such a method is good. For example, some behavioral characteristics and numbers of objects are initialized to null or indeterminate values are also reasonable, as well as linked lists, hash tables, graphs and so on data structures can be initialized to empty containers.
But not all objects belong to the above type, for many objects, it is unreasonable to not use external data for full initialization. For example, an address book object that has no name entered will have no meaning. In some companies, all devices must be labeled with a company ID number, so when an object is created to model a device, no appropriate ID number is provided, and the object created is meaningless.
In a perfect world, classes that create objects without any data can contain default constructors, and classes that require data to establish objects cannot contain default constructors. Alas! But our real world is not perfect, so we have to consider more factors. Especially if a class does not have a default constructor, there are some restrictions on usage.
Consider a class that represents a company's device, which contains a company ID code that is coerced as a constructor parameter:
class EquipmentPiece {
public:
EquipmentPiece(int IDNumber);
...
};
Because the Equipmentpiece class does not have a default constructor, it is problematic to use it in three different situations. The first scenario is when an array is created. In general, there is no way to pass arguments to a constructor when an array of objects is created. So in general, it is not possible to create an array of Equipmentpiece objects:
EquipmentPiece bestPieces[10]; // 错误!没有正确调用
// EquipmentPiece 构造函数
EquipmentPiece *bestPieces =
new EquipmentPiece[10]; // 错误!与上面的问题一样
But there are still three ways to avoid this limitation. For arrays that are not heap (non-heap arrays) (that is, the array is not allocated memory in the heap.) One of the solutions is to provide the necessary parameters when the array is defined: