The constructor of the class is automatically called when the object is generated, which is used to initialize the data member of the object. The destructor of the class is a function of "~" as a function name as the class name. It is called when the object is deleted, that is, the program performs the range of the exiting the initialization class object. The destructor itself does not actually delete the object, but the cleanup work before the system is abandoned, so that the memory can be used to save new objects.
The constructor is automatically called, and their call sequence depends on the order in which the execution process enters and leaves the object. Let's give a specific example to show their call sequence.
//create.h
#ifndef create_h
#define create_h
Class createandDestroy {
PUBLIC:
CreateAndDestroy (int); // Constructor
~ CreateandDestroy (); // destructor
Private:
Int data;
}
#ENDIF
//ceate.cpp
#include
#include "create.h"
CreateandDestroy :: CreateAndDestroy (int value)
{
Data = Value;
COUT << "Object" << Data << "established";
}
CreateAndDestroy :: ~ createandDestroy ()
{
COUT << "Object" << Data << "deStructor" << endl;
}
//create1.h
#include
#include "create.h"
Void Create (Void);
CreateAndDestroy first (1); // global object
int main ()
{
Cout << "(Global Object is established before main)" << Endl;
CreateAndDestroy Second (2); // Local object
Cout << "(partial automatic object is established inside the main function) << ENDL;
Static CreateAndDestroy Third (3); // Local object
COUT << "(local static object is established in main)" << Endl;
CREATE (); // Call CREATE () build an object
CreateAndDestroy FouRTH (4); // Local object
COUT << "(local automatic object establishment)" << endl;
Return 0;
}
Void Create (void)
{
CreateAndDestroy Fifth (5);
Cout << "(local automatic object is established in Create ())" << Endl;
Static CreateAndDestroy Sixth (6);
COUT << "(local static object is established in Create ())" << ENDL;
CreateandDestroy Seventh (7);
Cout << "(local automatic object is established in Create ())" << Endl;
}