3

for example I have in C++ a struct like

typedef struct point {
    double x, y;
};

I can use

point *p = new point;

or

point *p = new point();

To create a point dynamically.

Whats the difference? In the second case x and y are initialized implicit to zero. Why not in the first case?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
knowledge
  • 941
  • 1
  • 11
  • 26

1 Answers1

4

According to the C++ Standard (11.6 Initializers)

11 An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.

It means that data members of the structure of scalar types are zero-initialized in this statement

point *p = new point();

In this case

point *p = new point;

the members of the structure are default initialized that is (as the class has no user-defined constructor and the data members do not have initializers in the class definition) have indeterminate values.

Pay attention to that you could define the structure the following way

typedef struct point {
    double x = 0, y = 0;
};

In this case the result of the both statements above will be the same.

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