[C++ Study Notes]: Constructor Section

The order in which C++ calls destructors and constructors

Under normal circumstances, the order of calling destructors is exactly the opposite of the order of calling constructors. The constructor called first has its corresponding destructor called last, and the constructor called last has its corresponding destructor. The function is called first.

For objects defined in the C++ global scope, its constructor is called before all functions in the file are executed. However, if there are multiple files in a program and global objects are defined in different files, the constructors of these objects The execution order is uncertain. When the main function completes execution, the destructor is called.

If a local automatic object is defined, its constructor will be called when the object is created; if the function is called multiple times, the constructor will be called each time the object is created, and the destructor will be called first when the function call ends and the object is released. function.

If a static local object is defined in a function, the constructor will only be called once when the program calls this function for the first time to create an object. The object will not be released at the end of the call, so the destructor will not be called, only when the main function ends. , before calling the destructor.

C++ object array

In C++, arrays can be composed not only of simple variables, but also of objects. The compilation system will pass an actual parameter to the constructor of each object element.

Case: C++ uses object array to find volume

#include <iostream>
using namespace std;
class Box
{    public:      Box(int ​​h=3,int w=4,int l=5):height(h),width(w),length(l){}      // Declare a parameter constructor and use the parameter initialization table to initialize the data members   int volume();      private:int height,width,length; }; //Find the volume function int Box::volume() {   return height*width*length; } //The main function of the program int main( ) {   Box obj[2]={Box(1,2,3),Box(2,3,4)};//The array object   cout<<"The volume is:" <<obj[0].volume()<<endl;//Call the volume function   cout of obj[0]<<"The volume is:"<<obj[1].volume()<<endl;//Call The volume function of obj[1]    returns 0; }


















Compile and run results:

Volume is: 6
Volume is: 24

--------------------------------
Process exited after 0.7907 seconds with return value 0
please Press any key to continue. . . .

Guess you like

Origin blog.csdn.net/Jiangziyadizi/article/details/129569683