Understanding the default implicit default structure

I am trying to understand how the default constructor of the compiler works. I made this example:

#include <iostream>

class Base {
    public:
    int number;
};

class Test1 : public Base {  
};

class Test2 {
    public:
    Base base;
};

int main() {
    Test1 test1;
    Test2 test2;
    std::cout<<test1.number<<std::endl;
    std::cout<<test2.base.number<<std::endl;
}

The output of this test program is for test1 0, and for test2is an uninitialized (random) number. Now my question is: why, in the first case ( test1), the default constructor for the compiler initializes numberto 0, but test2not for?

Change . According to the answers, the behavior is undefined. So, in this program, what does the default constructor for the compiler do?

+4
source share
3 answers

8.5/12:

, . , , , , (5.17).

, int "-- " ยง8.5/7:

T :

  • T (, cv-qualit) ( 9), (12.1) T ( , T (13.3) , );
  • T - , ;
  • .
+5

number , . , test1 0 .

+3

, , . .

++ 11 (.. , ). 12.1, 6 (. 243) : " , ctor , ".

"ctor-initializer" " ", :

Test1::Test1() {}

Test2::Test2() {}

Base::Base() {}

So, both in Test1, and Test2, is Base::numbernever initialized ( Baseis, in Test2, but the Baseimplicit constructor does not initialize number).

At a minimum, the standard does not require initialization Base::number. Compilers are free to define things that the standard does not define. The fact that you see 0does not mean that the operation is defined in accordance with the standard, it just means that your compiler nullifies things in this particular case.

+1
source

Source: https://habr.com/ru/post/1534514/


All Articles