A constructor is a special class member function that is called when the class is instantiated. The destructor is a handler function after the object is used. By overloading a function, you can create multiple constructors with the same name. Typically, constructors are used to initialize the members of an object without declaring a type.
For example, the constructor prototype for the Name class:
<strong><span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >name (const char * fname, const * lname);</span></strong>
The methods of initialization are commonly used in the following ways:
<strong><span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >name one = Name ("Peter", "Lee"); Name ("Peter", "Lee"); Name *three = new name ("Peter", "Lee");</span></strong>
In c++11, you can use the 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 assignment statement is allowed to initialize it:
<strong><span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >classname Object = value;</span></strong>
If the object is instantiated without explicitly initializing it, the default constructor is called, and the default constructor has no parameters. If a default constructor is not provided in the program, the compiler automatically defines one. Otherwise, you must provide the default constructor yourself, you can have no arguments, and if so, you must provide default values for all parameters:
Name ();
Name (const char * fname = "Peter", const char * lname = "Lee");
When the destructor is out of scope, it plays a role in dealing with the funeral, which simply means releasing the memory. The name of the constructor is the same as the class name, and the name of the destructor must precede the class name with a "~" symbol; note that constructors and destructors cannot specify any return value types, including void return types;
C + + constructors and destructors summary