Difference destructors constructor

Constructor:

What is the constructor? Popular speaking, in the class, function name, class name and the same function called a constructor function. Its role is to create an object, do some initialization work (for example, data Initialization). C ++ allows functions of the same name, it allows multiple constructors in a class. If not one, the class compiler will generate a default constructor.

The only restriction is that the constructor syntax it does not specify a return type, not even void the line.

Constructor with no arguments: the name of the class is typically in the form of object name () {} function body

Constructor arguments: the constructor with no arguments, the initialization value only to fixed objects. Initialization parameters to the constructor of the more flexible, the parameter passed to the constructor, the object can be given different initial values. General form: constructor function name (parameter list);

When you create an object using: class name object name (argument list);

The initial value of the constructor parameters: the argument to the constructor may have a default value. When defining an object, if no argument is given automatically to the corresponding default parameter values assigned to an object. General form:
name of the constructor (Default = parameter, default parameter = value, ......);

Destructor:

When a class object goes out of scope, the destructor will be called (automatic call system). Destructor name and class name, but be preceded ~. For a class, it allows only a destructor, destructor not have parameters and returns no value. Destructor action is a complete cleaning work, such as to release the memory allocated from the heap.

A class can have multiple constructors, destructors but only one. Destructor objects sequentially, with the establishment of the reverse order, i.e. first the constructed object destructors.

1, different concepts:

Destructor: a function call where the object has been completed, the system automatically performs the destructor.

Constructor: is a special method. A particular class can have multiple constructors, they can be distinguished i.e. constructor overloads to make different types of parameters or the number of its parameters.

2, different roles:

Destructor: destructor is invoked.

Constructors: the initial value assigned to an object member variable

3, different purposes:

Destructor: "clean up the aftermath of" work

Constructor: mainly used to initialize the object when the object is created, the object member variable that is assigned the initial value, the total used in the statement to create an object with the new operator.

Published 137 original articles · won praise 44 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_38769551/article/details/105142822