C ++ constructor and destructor summary, constructor Summary
Constructor is a special class member function that is called during class instantiation. The Destructor is a processing function after the object is used. You can create multiple constructors with the same name through function overloading. In general, constructors are used to initialize the members of an object without declaring the type.
For example, the Name class constructor prototype:
<strong><span style="font-family:SimSun;font-size:18px;">Name(const char * fname, const * lname );</span></strong>
The following methods are commonly used for initialization:
<strong><span style="font-family:SimSun;font-size:18px;">Name one = Name("Peter", "Lee");Name two("Peter","Lee");Name *three = new Name("Peter", "Lee");</span></strong>
In C ++ 11, you can use list initialization:
<strong><span style="font-family:SimSun;font-size:18px;">Name one = Name{"Peter", "Lee"};Name two{"Peter","Lee"};Name *three = new Name{"Peter", "Lee"};</span></strong>
When the constructor has only one parameter, the value assignment statement can be used for initialization:
<strong><span style="font-family:SimSun;font-size:18px;">Classname object = value;</span></strong>
If the object is not explicitly initialized during Object Instantiation, the default constructor is called. The default constructor has no parameters. If no default constructor is provided in the program, the compiler automatically defines one. Otherwise, you must provide the default constructor by yourself. If there is no parameter, you must provide the default value for all parameters:
Name ();
Name (const char * fname = "Peter", const char * lname = "Lee ");
When an object is out of scope, the Destructor plays a role in dealing with the problem. Simply put, it is to release the memory. The constructor name is the same as the class name, And the Destructor name must be prefixed "~ "Symbol; Note: constructor and destructor cannot specify any return value type, including the void return type;