Question about initialization. The output must be zeros with C++11 and afterwards?

98 Views Asked by At

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?

1

There are 1 best solutions below

0
user12002570 On

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_shared with () aka value initialization which will value-initialize the object. This means the data member line will be value initialized here which will in turn value intialize its data members start and end. Finally, value initialization of start and end will zero its own data members x and y.

Case 2

Here we consider Demo demo;

Demo demo is default initialization and demo will be created using the defaulted default constructor which will use defalt constructor of line. Next, Line's default constructor will use default constructor of Point. Finally, Point's default constructor will be used which will leave the built in data member x and y uninitialized.

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 line will be zero initialized which in turn implies that start and end will also be zero initialized. This also means that the data members x and y will also be zero initialized.