Constructor and Destructor

Constructor, is a special method. It is mainly used to initialize the object when it is created, that is, to assign the initial value to the object member variable, and it is always used together with the new operator in the statement to create the object. A particular class can have multiple constructors, which can be distinguished according to the number of parameters or the type of parameters, that is, overloading of constructors.

Destructor (destructor) Contrary to the constructor, when the object ends its life cycle (for example, the function in which the object is located has been called), the system automatically executes the destructor. The destructor is often used to do the work of "cleaning up the aftermath" (for example, when creating an object, use new to open up a memory space, and delete will automatically call the destructor and release the memory).

 

If we don't write a destructor, C++ will automatically synthesize one for us, that is, C++ will automatically write a destructor for us. In many cases, the automatically generated destructor can work well, but for some important deeds, we must write the destructor ourselves. 
Destructor and constructor are a pair. Constructors are used to create objects, while destructors are used to destroy objects. Simply put: when an object is born, use the constructor, and when it dies, use the destructor.

 

Constructor and destructor calling sequence:

Parent class construction -> subclass construction -> subclass destruction -> parent class destruction

Or parent class construction -> member variable construction -> subclass construction -> subclass destruction -> member variable destruction -> parent class destruction

which is:

1. The base class has no default constructor, and the derived class must explicitly give the base class name and parameter list in the initialization list.
2. If the base class does not define a constructor, the derived class can also use the default constructor without defining it.
3. The base class defines a constructor with a formal parameter list, and the derived class must define a constructor.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324506674&siteId=291194637