First, the characteristics of the structure function
(1) A constructor is a special member function of a class, and the function name is the same as the class name;
(2) The Access property of the constructor should be the publicaccess attribute;
(3) The function of the constructor is to initialize the object, so in the constructor can only initialize the data members, these data members are generally private members, in the constructor generally do not do anything other than initialization;
(4) constructors can be defined within a class or outside the class;
(5) The constructor has no function return type. Note: Do not write anything, nor can write void;
(6) when the program is running, when a new object is created, the constructor of the class to which the object belongs is automatically called, which is called only once during the lifetime of the object.
(7) constructors can be overloaded. A class can have more than one constructor, which is distinguished by a different parameter table, and the system is selected for execution by the rules of the general function overload when it is called automatically.
Ii. initializing a data member using an initialization table
Initialize the general format of the table:
Class name :: constructor function name ( parameter list ): Initialize table
{
constructor other implementation code
}
Format of the initialization table:
Object Member 1 ( parameter name or constant ), object member 2 ( parameter name or constant ), ... Object into
Member N ( parameter name or constant )
For example , the constructor defined by 1.4 can use the following form:
Cdate:: Cdate (int y, int m,int D): Year (y), month (m), day (d) {}
Note: This kind of writing is convenient and concise. Many C + + programmers like to initialize all data members in this way. Other member functions of the class can use the initialization table as needed, except that the constructor can use the initialization table.
First, the function of the destructor
is a special class member function that acts in contrast to a constructor function. The function of a destructor is to perform the cleanup automatically before the end of the object lifetime.
For example:
A class may allocate resources in the constructor, which are freed before the end of the object's lifetime, and freeing the resource is done automatically by invoking the class's destructor.
Second, the characteristics of the destructor function
(1) The name of the destructor function is special, it is the class name plus the "~" character, which indicates that it is opposite to the constructor function;
(2) The destructor has no parameters and cannot specify a return value type;
(3) only one destructor can be defined in a class, so the destructor cannot be overloaded;
(4) The system automatically calls the destructor at the end of the object lifetime.
Constructors and destructors in C + +