473,611 Members | 2,236 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

static const member initialization

Hello everyone,

I have a Packet class I use to send packets over the Internet. All the
packets sent in a session are supposed to share a common random ID.

I figured I'd use a static const member inside my class.

class Packet
{
static const int session_id;
...
};

My problem is: where (and when) do I initialize session_id.

On my first try, I added the following statement in packet.cpp

const int Packet::session _id = rand();

But, as far as I understand, this initialization occurs before main()
starts, thus, before I can call srand().

Therefore, this implementation seems incorrect.

I suppose I can use the so-called "construct-on-first-use" idiom
from the C++ FAQ.

http://www.parashift.com/c++-faq-lit...html#faq-10.16

Are there other ways?
(Remember: I'm supposed to call srand() only once.)

Regards.
Dec 30 '06 #1
7 4015
"Spoon" <root@localhost wrote in message
news:45******** *************@n ews.free.fr
Hello everyone,

I have a Packet class I use to send packets over the Internet. All the
packets sent in a session are supposed to share a common random ID.

I figured I'd use a static const member inside my class.

class Packet
{
static const int session_id;
...
};

My problem is: where (and when) do I initialize session_id.

On my first try, I added the following statement in packet.cpp

const int Packet::session _id = rand();

But, as far as I understand, this initialization occurs before main()
starts, thus, before I can call srand().

Therefore, this implementation seems incorrect.

I suppose I can use the so-called "construct-on-first-use" idiom
from the C++ FAQ.

http://www.parashift.com/c++-faq-lit...html#faq-10.16

Are there other ways?
How about:

class Packet
{
static const int session_id;
};

int InitializeStati c(unsigned seed)
{
srand(seed);
return rand();
}

const int Packet::session _id = InitializeStati c(5);
--
John Carson
Dec 30 '06 #2
Can a function be called in a static member initialization ? I thought
static member initialization should be constants.

Dec 31 '06 #3
John Carson wrote:
Spoon wrote:
>>I have a Packet class I use to send packets over the Internet. All the
packets sent in a session are supposed to share a common random ID.

I figured I'd use a static const member inside my class.

class Packet
{
static const int session_id;
...
};

My problem is: where (and when) do I initialize session_id.

On my first try, I added the following statement in packet.cpp

const int Packet::session _id = rand();

But, as far as I understand, this initialization occurs before main()
starts, thus, before I can call srand().

Therefore, this implementation seems incorrect.

I suppose I can use the so-called "construct-on-first-use" idiom
from the C++ FAQ.

http://www.parashift.com/c++-faq-lit...html#faq-10.16

Are there other ways?

How about:

class Packet
{
static const int session_id;
};

int InitializeStati c(unsigned seed)
{
srand(seed);
return rand();
}

const int Packet::session _id = InitializeStati c(5);
Hello John,

The problem with this solution is that I have other classes that call
rand(). I don't want to make class Packet responsible for initializing
the RNG. For example, if I don't use Packet in one of my programs, and
if I also use the other classes, the RNG will always be seeded with 0.

The solution I'm looking for is:
call srand in main
all static const members are initialized after that point.

Does someone know how to do that?

Regards.
Dec 31 '06 #4
"subramania n" <su************ **@yahoo.comwro te in message
news:11******** *************@v 33g2000cwv.goog legroups.com
Can a function be called in a static member initialization ?
Yes.
I thought static member initialization should be constants.
Why?
--
John Carson
Dec 31 '06 #5
"Spoon" <ro**@127.0.0.1 wrote in message
news:45******** *************@n ews.free.fr
John Carson wrote:
>Spoon wrote:
>>I have a Packet class I use to send packets over the Internet. All
the packets sent in a session are supposed to share a common random
ID. I figured I'd use a static const member inside my class.

class Packet
{
static const int session_id;
...
};

My problem is: where (and when) do I initialize session_id.

On my first try, I added the following statement in packet.cpp

const int Packet::session _id = rand();

But, as far as I understand, this initialization occurs before
main() starts, thus, before I can call srand().

Therefore, this implementation seems incorrect.

I suppose I can use the so-called "construct-on-first-use" idiom
from the C++ FAQ.

http://www.parashift.com/c++-faq-lit...html#faq-10.16

Are there other ways?

How about:

class Packet
{
static const int session_id;
};

int InitializeStati c(unsigned seed)
{
srand(seed);
return rand();
}

const int Packet::session _id = InitializeStati c(5);

Hello John,

The problem with this solution is that I have other classes that call
rand(). I don't want to make class Packet responsible for initializing
the RNG. For example, if I don't use Packet in one of my programs, and
if I also use the other classes, the RNG will always be seeded with 0.

The solution I'm looking for is:
call srand in main
all static const members are initialized after that point.

Does someone know how to do that?
It can't be done.

A version of "construct-on-first-use", as you previously suggested, would
seem to be your best bet, e.g.,

class Packet
{
static const int session_id;
};

int InitializedRand (unsigned seed=0)
{
static bool needInitializat ion = true;
if(needInitiali zation)
{
srand(seed);
needInitializat ion = false;
}
return rand();
}

const int Packet::session _id = InitializedRand (5);

In use, you would call InitializedRand in place of your first call to rand()
for the initialization of *each* static variable that requires it.

In case there aren't any static variables requiring rand(), you would also
use it in place of your first call to rand() from main() (which is most
simply accomplished by always calling it at the start of main() ). As an
alternative to this call from main, you might choose to have an object that
is a static variable in every program that you write --- an "applicatio n"
object --- and call the function in its initialization.
--
John Carson


Dec 31 '06 #6
John Carson wrote:
subramanian wrote:
>Can a function be called in a static member initialization ?

Yes.
>I thought static member initialization should be constants.

Why?
In C, AFAIU, objects with static duration must be initialized with
static initializers, i.e. expressions that the translator can evaluate
prior to program startup.

http://www-ccs.ucsd.edu/c/declare.html
Dec 31 '06 #7
"Spoon" <ro**@127.0.0.1 wrote in message
news:45******** *************@n ews.free.fr
John Carson wrote:
>subramanian wrote:
>>Can a function be called in a static member initialization ?

Yes.
>>I thought static member initialization should be constants.

Why?

In C, AFAIU, objects with static duration must be initialized with
static initializers, i.e. expressions that the translator can evaluate
prior to program startup.

http://www-ccs.ucsd.edu/c/declare.html

It makes sense that C++ would not follow C in this respect. Objects of class
type all have constructors to initialize them. Thus if any object of class
type is static, it is initialized by a function (i.e., the constructor) even
where no function is explicitly called.

It would be very inconvenient if the permitted form of initialization for
class objects differed depending on whether they were static variables.

--
John Carson
Dec 31 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
2861
by: cppaddict | last post by:
I have class with two static member objects, one of type int and one of type vector<int>. static int myStaticMemberInt static vector<int> myStaticMemberVector; I know how to initialize the int member: MyClass::myStaticMemberInt = 99;
3
3594
by: DanielBradley | last post by:
Hello all, I have recently been porting code from Linux to cygwin and came across a problem with static const class members (discussed below). I am seeking to determine whether I am programming non-standard C++ or if the problem lies elsewhere. To summarize static const class members are not being accessed properly when accessed from a DLL by another external object file (not within the DLL). It only occurs when the static const...
5
1702
by: Minti | last post by:
How do we initialize static const data in C++, I tried class Foo { static const std::string name = "MyName"; }; I don't see any reason as to why this must not work.
2
9277
by: utab | last post by:
Dear all, I am confused at some point on the initialization of static map member of a class. The class I have designed id something like this. class Class_name{ public: private:
8
8919
by: Per Bull Holmen | last post by:
Hey Im new to c++, so bear with me. I'm used to other OO languages, where it is possible to have class-level initialization functions, that initialize the CLASS rather than an instance of it. Like, for instance the Objective-C method: +(void)initialize Which has the following characteristics: It is guaranteed to be run
10
4191
by: n.torrey.pines | last post by:
Are global variables (and const's) guaranteed to be initialized before static class members (and methods) ? const int x = 19907; int get_x() { return x; } // another compilation unit: int get_x();
9
8876
by: Jess | last post by:
Hello, I was told that if I declare a static class constant like this: class A{ static const int x = 10; }; then the above statement is a declaration rather than a definition. As I've *defined* "x"'s value to be 10, isn't above statement a
15
7852
by: akomiakov | last post by:
Is there a technical reason why one can't initialize a cost static non- integral data member in a class?
2
2474
by: Ranganath | last post by:
Hi, Why is there a restriction that only integral types can be made static constant members of a class? For e.g., class B { private: static const double K = 10; };
0
8097
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8561
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8240
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8411
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5527
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4042
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2546
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1692
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1411
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.