Initialization in list - default value

228 views Asked by At

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?

2

There are 2 answers

0
AnT stands with Russia On BEST ANSWER

Yes, it does. Just like

double d = double();
double *p = new double();

will initialize d with 0 and allocate *p initialized with 0.

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 do

double d{};

which declares variable d initialized with 0.

0
Olivier Poulin On

When you do _Field() you perform a zero initialization I believe.