0

Considering the following class definition:

class Foo {    
private:
    int a;
    int b;

public:
    Foo() : 
        a()
    {}
};

If I recall correctly, a() will call the default constructor of int and initialize it to 0. If I leave out the constructor, it's undefined what happens to the member variables. But what about b in this example? For my version of gcc it seems to be set to 0 as well, but is that defined behaviour?

Thanks for your answers.

Felix
  • 6,885
  • 1
  • 29
  • 54

2 Answers2

3

b will be un-initialized, so attempting to use it causes UB (undefined behaviour). It just happened that your member was set to zero by gcc, but you should not rely on this.

In fact, if you compile with all warnings on (-Wall -Wextra -Wpedantic), gcc spits out

warning: 'foo.Foo::b' is used uninitialized in this function

when trying to do something like

cout << foo.b; // assuming b is public here
vsoftco
  • 55,410
  • 12
  • 139
  • 252
0

According to the standard, it is undefined, and initialized to any value that used to occupied the memory block that it now occupies. However, some compliers automatically initialize values to the zero value for that type.

Look at the accepted answer to this question:

What happens to a declared, uninitialized variable in C? Does it have a value?

Community
  • 1
  • 1
パスカル
  • 479
  • 4
  • 13