About synthesized default constructor?

A compiler auto created default constructor is called a synthesized default constructor. It will initialize the built-in members to 0 or not depends on where the class object is defined? Is that a correct understanding?

if I define a class

1
2
3
4
class point{
public:
  double x, y;
};


if I define point point1; in global scope then point1.x and point1.y will be initialized to 0, if I define point point2; in a local scope, then its x and y won't be initialized? Correct?

If it is like this, then I believe if there are built-in type members in a class, then the synthesized default constructor is almost useless! right? Thanks.
It doesn't matter. Zeroing the memory of an object isn't always the most useful thing for initialization anyway.

Instead, you should always make sure your class initializes its data.

(In other words, yes, you should write your own default constructor.)
An object with a trivial constructor can be value initialized when zero initialization is required.
http://en.cppreference.com/w/cpp/language/value_initialization


> then the synthesized default constructor is almost useless! right?

For
1
2
3
4
class point{
public:
  double x, y;
};

the implicitly-declared default constructor is trivial; no synthesized constructor is generated.


> if I define point point1; in global scope then point1.x and point1.y will be initialized to 0

Yes. The point object would be value initalized.


> if I define point point2; in a local scope, then its x and y won't be initialized? Correct?

Yes. It does not have a static storage duration and point has a trivial constructor.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <vector>

class point{
public:
  double x, y;
};

int main()
{
    static point a ; // a is value initialized => a.x and a.y are zero initialized

    point b ; // b is uninitialized => b.x and b.y are uninitialized

    point c{} ; // c is value initialized => c.x and c.y are zero initialized

    std::vector<point> seq(20) ; // the 20 point objects in the vector are value initialized

    point* d = new point ; // the point object is uninitialized
    point* e = new point() ; // the point object is value initialized
    point* f = new point{} ; // the point object is value initialized

    std::cout << a.x << ' ' << c.y << ' ' << seq[5].x << ' ' << e->x << ' '  << f->y << '\n' ;
}

http://coliru.stacked-crooked.com/a/bcf5191f0f64e951
Thanks, JLBorges!
Topic archived. No new replies allowed.