Bjarne Strousrup in The C++ Programming Language illustrates the use of static members of a class with code similar to this:
class Date{
int d, m, y;
static Date default_date;
public:
Date(int dd=0, int mm=0, int yy=0);
static void set_default(int, int, int);
int year()const{return y;}
int month() const{return m;}
int day() const {return d;}
};
Date::Date(int dd, int mm, int yy){
d=dd ? dd : default_date.d;
m=mm ? mm : default_date.m;
y=yy ? yy : default_date.y;
}
void f()
{
Date::set_default(4,5,1945);
}
Date Date::default_date(16,12,1770);
void Date::set_default(int d,int m, int y)
{
Date::default_date=Date(d,m,y);
}
int main(){
Date ob(5,5);
cout<<ob.day()<<endl<<ob.month()<<endl<<ob.year();
return 0;
}
The output of the code was
5
5
1770
He states that the default_date must be defined somewhere, as it is done between f() and
set default. While we are at it can somebody tell me why is it with two Date before :: and not one?
OK default_date can be constructed with the constructor provided since all arguments are supplied.
Now i tried removing the year from the list of arguments for default_date:
Date Date::default_date(16,12);
and the program compiled fine with output 5,5,0. This means that when in the constructor, since the last argument is not provided yy is 0 and default_date.y should get default_date.y and it turns out that it is 0. To me this only makes sense if the members of default_date are set to 0 when default_date is declared, and changed when default_date is defined. If that is true why then must we define default_date, why cant we leave it be 0,0,0?