Search code examples
c++default-constructor

Understanding implicitly declared default costructor


I'm trying to understand how the compiler's default constructor 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 test2 is a uninitialized (random) number. Now my question is: why in the first case (test1) the compiler's default constructor initialize number to 0 but for test2 it doesn't?

Edit: According to answers both makes undefined behavior. So, in this program, what the compiler's default constructor does?


Solution

  • The value of an uninitialized object is indeterminate as per 8.5/12:

    If no initializer is specified for an object, the object is default-initialized. When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced (5.17).

    Unfortunately for you, int falls into the category of "non-default-initialized types" as per §8.5/7:

    To default-initialize an object of type T means:

    • if T is a (possibly cv-qualified) class type (Clause 9), the default constructor (12.1) for T is called (and the initialization is ill-formed if T has no default constructor or overload resolution (13.3) results in an ambiguity or in a function that is deleted or inaccessible from the context of the initialization);
    • if T is an array type, each element is default-initialized;
    • otherwise, no initialization is performed.