Learning C ++ constructor and Destructor from scratch (1): constructor, destructor, assignment and initialization, and explicit keywords

Source: Internet
Author: User

1. constructor and default constructor

(1) constructor

Constructor is a special member function.
Creates a new object of the class type. The system automatically calls the constructor.
The constructor is used to ensure that every data member of an object is correctly initialized.

The function name and class name are identical.
You cannot define the type (return type) of the constructor or use void.
In general, constructor should be declared as a public function, which is generally called implicitly.
The constructor is declared as private for special purposes, such as the singleton mode.
Constructor can have any type and any number of parameters. A class can have multiple Constructor (overload)

(2) default constructor

Constructors without Parameters
If the program is not declared, the system automatically generates a default constructor, which is an empty function.

If the program implements any Constructor (including the copy constructor), the compiler will no longer provide the default constructor.

C ++ code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Ifndef _ test_h _
# DEFINE _ test_h _

Class Test
{
Public:
// If the class does not provide any constructor, the system will provide us with
// Default constructor
Test ();
Test (INT num );
Void display ();

Test & operator = (const Test & other );

~ Test ();
PRIVATE:
Int num _;
};
# Endif/_ test_h _

C ++ code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# Include "test. H"
# Include <iostream>
Using namespace STD;

// A constructor without parameters is called the default constructor.
Test: Test ()
{
Num _ = 0;
Cout <"Initializing default" <Endl;
}

Test: Test (INT num)
{
Num _ = num;
Cout <"Initializing" <num _ <Endl;
}

Test ::~ Test ()
{
Cout <"Destroy" <num _ <Endl;
}

Void test: Display ()
{
Cout <"num =" <num _ <Endl;
}

Test & test: Operator = (const Test & other)
{
Cout <"test: Operator =" <Endl;
If (this = & other)
Return * this;

Num _ = Other. Num _;
Return * this;
}


C ++ code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Include "test. H"

Int main (void)
{
Test T;
T. Display ();

Test T2 (10 );
T2.display ();

Test * T3 = new test (20); // new operator
T3-> display ();

Delete T3;

Return 0;
}

In the above program test, the output is:


We can see that the constructor is automatically called, and the constructor can be called in heavy load; when the object lifetime on the stack is reached, the Destructor will be automatically called; while new operator does two things, one is to create the object memory, the other is to call the constructor; the memory on the stack needs to be deleted and released. The first is to call the destructor, and the second is to release the memory.


// We cannot call a constructor but do not provide parameters (instantiated object), as shown in
A ();
// Because it is ambiguous, we can also regard it as declaring a function a without parameters, and the return value is an object of type.

However, when passing parameters in a function, you can write as follows: A () // defines an unknown object.


Note that the construction of a global object is prior to the execution of the main function, as shown below:

C ++ code
1
2
3
4
5
6
7
8
9
10
11
12
# Include "test. H"
# Include <iostream>
Using namespace STD;

Test T (10 );

Int main (void)
{
Cout <"entering Main..." <Endl;
Cout <"exiting main..." <Endl;
Return 0;
}

When return 0, the lifetime of the global variable is reached, so the Destructor is automatically called.


Ii. destructor

The function name and class name are similar (one character "~" is added before).
No return type
No Parameters
The Destructor cannot be overloaded.
If no destructor is defined, the compiler automatically generates a default destructor in the following format:
Class Name ::~ Default destructor name ()
{
}
The default destructor is an empty function.

C ++ code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Include "test. H"

Int main (void)
{
Test T [2] = {10, 20 };

Test * t2 = new test (2 );
Delete T2;

Test * T3 = new test [2];
Delete [] T3;

Return 0;
}

Note that test T [2] = {10, 20 };
In, 20 is passed to the constructor of each object as a parameter. If there is no corresponding constructor, for example, if there are only two constructor parameters, the compilation fails.


In fact, constructor and destructor can both be explicitly called, but this is rarely done. For more information, see here.


Iii. Conversion Constructor

The constructor of a single parameter is not necessarily a conversion constructor.
Convert other types to class types
Class constructor has only one parameter, because the compiler can use this constructor to implicitly convert the parameter type to the class type.

C ++ code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Include "test. H"

Int main (void)
{
Test T (10); // a constructor with a parameter acting as a normal Constructor

T = 20; // assign the integer 20 to the T object.
// 1. Call the conversion constructor to convert the integer 20 to the class type (generate a temporary object)
// 2. assign a temporary object to the T object (the = Operator is called)

Test T2;

Return 0;
}


We can see that a temporary object is initialized, the parameter 20 is passed, the value assignment operator = is called, the temporary object is released, and the last released object is the modified T. The format of the value assignment operator is: Test & test: Operator = (const Test & Other). In fact, if you do not implement it yourself, the compiler will also implement a default value assignment operator, what we do is the same as what we implement.


Iv. Differences Between Assignment and initialization

The equal sign in the initialization statement is not an operator.

C ++ code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Include "test. H"

Int main (void)
{
Test T = 10; // equivalent to test T (10); here, = is not an operator, indicating initialization.

T = 20; // value assignment operation

Test T2;
T = t2; // value assignment operation T. Operator = (T2 );

Return 0;
}


The first statement is initialization, followed by the value assignment operation. Refer to the creation and destruction of the temporary object above. The call of the value assignment operator can understand the output.


5. Explain keywords

Only the keywords used by the class constructor.
The compiler does not use the constructor declared as explicit for implicit conversion. It only displays the created object in the program code.


Assume that the test (INT num) constructor of the test class is added with the explicit keyword before, test T = 10; or T = 20; such statements are not compiled, because implicit conversion is not allowed.


Refer:

C ++ primer version 4
Valid tive C ++ 3rd
C ++ programming specifications

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.