I am newbie to C++ and pretty confused about initialization of local variables for built-in and class types.
Here's a snippet of the code:
1 #include <iostream>
2 using namespace std;
3
4 class A {
5
6 public :
7 A() : x(9) {};
8 int x;
9
10 };
11
12 A global_a;
13 int global_b;
14
15 int main() {
16
17 A local_a;
18 int local_b;
19 cout << "global_a.x = " << global_a.x << '\n';
20 cout << "local_a.x = " << local_a.x << '\n';
21
22 cout << "global_b = " << global_b << '\n';
23 cout << "local_b = " << local_b << '\n';
24
25 }
Results using my g++ compiler on ubuntu linux:
global_a.x = 9
local_a.x = 9
global_b = 0
local_b = 0
I do think local_b should be undefined but somehow compiler initialized it by default. However local_a .. i am not sure if that should be initialized by default. From the testing here .. local_a seem to be initialized. Not sure if that complies with standard c++ specification (eg C++ PRimer 4th edition says default constructor is used regardless where a class variable is declared - does that means variable of class type is initialized whether it is global or local?).