Long time java programmer here, new to C++. I have been working with C-style "traditional" arrays (similar to arrays in java). I understand in C++ we can create a simple array as follows:
Person people[3];
The contents of this array is essentially uninitialized junk values. When I print out the contents of each element in the array, I (believe) am getting the memory address of each element.
for(int i = 0; i < 3; i++){std::cout << &person[i] << std::endl;}
Results:
//Note, I get different results here when I use an enhanced for loop vs an iterator for loop. Weird.
00EFFB6C
00EFFBA8
00EFFBE4
Now, here is the part I have failed to get a clear explanation on. I create a pointer to one of the elements in the array. I then ask for some value back from that pointer. In java, I would expect to get a null pointer, but in C++, that is not happening.
Instead, I get the default value, as though this element is initialized:
Person* person1Ptr = &people[0];//Points to an uninitialized value
std::cout << person1Ptr->getFirstName() << std::endl;//Output: "Default First Name", expected nullptr
When I try to get the first name of an element using a reference, this doesn't work (presumably because the value doesn't exist).
Full paste of code: https://pastebin.com/cEadfJhr
From my research, C++ does NOT fill arrays with objects of the specified type automagically.
How is my person1Ptr returning a value?
Person people[3];the initial state of the 3Personelements depend on whatPersonis. If it is aclasstype they will be default initialized. Whether or not that means there is uninitialized data depends on howPersonis implemented.Personis some form of handle to an instance ofPerson. In the case ofPerson people[3];you have three actual instances ofPersonno matter what. What you may be thinking of is that C++ might not initialize those objects to a meaningful value. Whether or not that happens depends on the details ofPerson.Personthat produces the behavior you witnessed. It is difficult to answer the question specifically without knowing more about your test.Personis aclasstype with a default constructor, so all three elements get default constructed.