-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path005 Data Member Initialization.cpp
88 lines (65 loc) · 1.39 KB
/
005 Data Member Initialization.cpp
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include<string>
struct Widget
{
int i; // Uninitialized
std::string s; // Default-initialized
int* pi; // Uninitialized and problematic
};
struct Widget2
{
int i; // Initialized to 0
std::string s; // Default-initialized
int* pi; // Uninitialized and problematic
};
struct Widget3
{
Widget3() {} // Explicit default constructor
int i; // Uninitialized
std::string s; // Default (i.e., empty string)
int* pi; // Uninitialized
};
int main()
{
Widget w; // Default initialization
Widget2 w2{}; // Value initialization
Widget3 w3{}; // Value initialization
}
//less reccomended
struct Widget4
{
Widget4()
{
i = 42; // Assignment, not initialization
s = "CppCon"; // Assignment, not initialization
pi = nullptr; // Assignment, not initialization
}
int i;
std::string s;
int* pi;
};
//
struct Widget5
{
Widget5()
: Widget5(42) // apply my general constructure with more arguments
//: i {42} // Initializing to 42
//, s {"CppCon"} // Initializing to "CppCon"
//, pi {} // Initializing to nullptr
{
}
Widget5(int x)
: i { x } // Initializing to x
, s {"CppCon"} // Initializing to "CppCon"
, pi {} // Initializing to nullptr
{}
int i;
std::string s;
int* pi;
};
//
struct Widget6
{
int i {42}; // Initializing to 42
std::string s {"CppCon"}; // Initializing to "CppCon"
int* pi {}; // Initializing to nullptr
};