0

I write this test code:

#include <iostream>
using namespace std;

class Date {
    int d;
    int m;
    int y;

public:
    static Date default_date;

public:
    Date(int d, int m, int y) {
        default_date.display();
        this->d = d ? d : default_date.d;
        this->m = m ? m : default_date.m;
        this->y = y ? y : default_date.y;
    }
    void display() { std::cout << d << "-" << m << "-" << y << std::endl; }
};

Date Date::default_date(25, 12, 2018);

int main() {
    Date d = Date(0, 0, 0);
    d.display();
    Date::default_date.display();
}

and the output is:

0-0-0
25-12-2018
25-12-2018
25-12-2018

OK, here is my question.

The static member default_date is initialized outside the class definition and using the constructor of class.

However, when the constructor is called, it seems that default_date already exists. I even execute default_date.display() and get the output 0-0-0.

Why I can visit default_date before it is constructed/initialized?

1 Answers1

2

The first time the constructor is called is the point of initialization of default_date. And inside this constructor, before the members are assigned their supposed values, the constructor constructor calls display(), which prints zero-initialized values of the members.

Ruslan
  • 18,162
  • 8
  • 67
  • 136
  • Class statics aren't initialised on construction, they are initialised on program start, otherwise classes with statics that aren't ever constructed will never be initialised – Alan Birtles Oct 30 '18 at 09:23
  • @AlanBirtles see the question to which this one is marked as duplicate: the storage for them is zero-initialized before any other initialization. – Ruslan Oct 30 '18 at 09:28
  • Ah, I see now I misread your answer – Alan Birtles Oct 30 '18 at 10:23