0

Let's assume the following class Foo.

struct Foo
{
  int i;
  bool j;
};

Why do I get different results from the following lines?

int main(void)
{
    //I thought the default constructor would be called
    Foo foo1;
    cout << foo1.i << " : " << foo1.j << endl; // " 4196352 : 0 " --> ctor not called?

    //if calling the default constructor explicitly
    foo1 = Foo(); 
    cout << foo1.i << " : " << foo1.j << endl; // " 0 : 0" --> ctor called.
}

Shouldn't the default ctor be implicitly called?

According to cpp reference:

If no user-declared constructors of any kind are provided for a class type (struct, class, or union), the compiler will always declare a default constructor as an inline public member of its class.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Guillaume D
  • 2,202
  • 2
  • 10
  • 37
  • implicitly defined (by the compiler) default constructor of a class does not initialize members of built-in types. `fundamental types` are not initialized by default (except some cases which depend on linkage -- global variables for example) – KostasRim Jul 22 '19 at 12:27
  • You can’t call a constructor explicitly; they don’t even have names. – molbdnilo Jul 22 '19 at 12:36
  • yes it does, Foo() is the default ctor for the class Foo – Guillaume D Jul 22 '19 at 12:38
  • @GuillaumeD No, it's not – it's an expression that value-initialises a temporary object. (To quote The Standard: "Constructors do not have names.") The object-creation syntax just happens to look very similar to the constructor-declaration and -definition syntax. – molbdnilo Jul 22 '19 at 21:06

1 Answers1

3

According to the C++ Standard

The implicitly-defined default constructor performs the set of initializations of the class that would be performed by a user-written default constructor for that class with no ctor-nitializer (15.6.2) and an empty compound-statement.

The class has a trivial default constrictor that does not initializes members of the class. So they have indeterminate values.

This form of a call of a construtor

Foo()

value initializes data members. For fundamental types it means zero-initialization.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335