how to initialize static member

S

subramanian

I saw the following code in Bjarne Stroustrup's 3rd edition of the book
The C++ Programming Language(NOT the special 3rd edition) - Pages228
and 229, related to static members.

I am giving the code only partly:

class Date {

int d, m, y;
static Date default_date;

public:
Date(int dd=0, int mm=0, int yy=0);
....
};

Date::Date(int dd, int mm, int yy)
{
....
}

Date Date::default_date(16, 12, 1770);
--------------------------------------------------------------

MY DOUBTS:
Here, does default_date(16, 12, 1770) call the constructor
Date::Date(int dd, int mm, int yy) ?

Is contructor called for static memebrs ?
 
S

Salt_Peter

subramanian said:
I saw the following code in Bjarne Stroustrup's 3rd edition of the book
The C++ Programming Language(NOT the special 3rd edition) - Pages228
and 229, related to static members.

I am giving the code only partly:

class Date {

int d, m, y;
static Date default_date;

public:
Date(int dd=0, int mm=0, int yy=0);
...
};

Date::Date(int dd, int mm, int yy)
: d(dd), m(mm), y(yy) // missing init list
{
...
}

Date Date::default_date(16, 12, 1770);
--------------------------------------------------------------

MY DOUBTS:
Here, does default_date(16, 12, 1770) call the constructor
Date::Date(int dd, int mm, int yy) ?

Is contructor called for static memebrs ?

Yes, it invokes the ctor.
The static member's ctor can only be invoked that way.
The init list is crucial.
replace with the following and observe...
#include <iostream>
....
Date::Date(int dd, int mm, int yy)
: d(dd), m(mm), y(yy) // missing init list
{
std::cout << "Date(int, int, int)\n";
}
You should declare a default date in main to see how that static member
is used to default initialize an instance of the class - however, you
did not show that part of the code.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top