Question about initialization. The output must be zeros with C++11 and afterwards for the code snippet below?
#include <iostream>
#include <memory>
struct Point{int x;int y;};
struct Line {Point start; Point end;};
class Demo{
public:
Demo() = default;
Line line;
};
int main()
{
auto ptr = std::make_shared<Demo>();
std::cout << ptr->line.start.x << std::endl;
std::cout << ptr->line.start.y << std::endl;
Demo demo;
std::cout << demo.line.start.x << std::endl;
std::cout << demo.line.start.y << std::endl;
Demo demo1{};
std::cout << demo1.line.start.x << std::endl;
std::cout << demo1.line.start.y << std::endl;
}
I am rellay confused now. Could someone shed some light on this matter?
Let us consider each case separately.
Case 1
Here we consider
auto ptr = std::make_shared<Demo>();.In this case you're using
make_sharedwith()aka value initialization which will value-initialize the object. This means the data memberlinewill be value initialized here which will in turn value intialize its data membersstartandend. Finally, value initialization ofstartandendwill zero its own data membersxandy.Case 2
Here we consider
Demo demo;Demo demois default initialization anddemowill be created using the defaulted default constructor which will use defalt constructor ofline. Next,Line's default constructor will use default constructor ofPoint. Finally,Point's default constructor will be used which will leave the built in data memberxandyuninitialized.Case 3
Here we consider
Demo demo1{};This is zero initialization(aka list initialization) and will also as the name suggests, zero initialize the data members. This means the data member
linewill be zero initialized which in turn implies thatstartandendwill also be zero initialized. This also means that the data membersxandywill also be zero initialized.