I've got this code sample:
#include <iostream>
using namespace std;
class Polygon
{
private:
double _Field;
public:
Polygon(): _Field(){}
void show_field(){ cout << _Field << endl; }
};
int main()
{
Polygon P1;
P1.show_field();
return 0;
}
I'm just wondering why does show() method always shows me 0 value? Does initialization in list
Polygon(): _Field(){}
initialize given field with 0 by default if there is no argument present?
Yes, it does. Just like
will initialize
d
with0
and allocate*p
initialized with0
.The
()
initializer stands for value-initialization in C++, which boils down to zero-initialization for scalar types. It is not in any way restricted to constructor initializer lists. It can be used in a variety of other contexts.It worked that way in C++ since the beginning of standardized times, except that in pre-C++03 versions of the language there was no such thing as value-initialization. In C++98 the
()
initializer triggered default-initialization, which also zeroed-out scalar types.In modern C++ (C++11 and later) you can use
{}
initializer instead of()
initializer to achieve the same effect. With{}
you can also dowhich declares variable
d
initialized with0
.