473,729 Members | 2,074 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Initialize static members outside the class

Hi,

Supposing a class get a complicated static member foo, and it need to
be initialized before any method of the class can be called, where
should I put these initialization code? I don't want to put them in
main(), it's so far away.

Thanks.

-
narke
Jul 15 '08 #1
9 3413
On Tue, 15 Jul 2008 01:57:51 -0700, Steven Woody wrote:
Hi,
Supposing a class get a complicated static member foo, and it need tobe
initialized before any method of the class can be called, where should
The question is how to define these initialise. *You know, for a
simple member, I can
do something like:
* *int MyClass::myMemb er = 123;
but for complicated non-POD types, such as a std::vector, how do I
initialize it by
push_back() many elements into it? * You see my problem? *Thanks.
Define in one place the same as you would the 'myMember' object.
Initialize in the constructor; that must be called before any methods
of the class.

Of course, you could just add the following:
std::vector<int NonPOD::foo(SIZ E,4.4); // initialize to 4.4

Joe Cook
Jul 15 '08 #2
On Tue, 15 Jul 2008 03:05:13 -0700, Steven Woody wrote:
On Jul 15, 5:40 pm, Lionel B <m...@privacy.n etwrote:
>On Tue, 15 Jul 2008 01:57:51 -0700, Steven Woody wrote:
Hi,
Supposing a class get a complicated static member foo, and it need to
be initialized before any method of the class can be called, where
should

^^^^^^
I presume you mean non-static method
I put these initialization code? I don't want to put them in main(),
it's so far away.

IIRC, a static class data member will be initialised before entering
main(), so as long as you don't instantiate any class objects before
entering main() you'll be ok*.

Then it depends how you organise your code, really. A common scenario
is that you'd have a class Myclass, say, declared in the header
myclass.hpp and with definitions in the compilation unit myclass.cpp.
In which case, it seems appropriate to define and initialise your
static members in myclass.cpp.

The question is how to define these initialise. You know, for a simple
member, I can
do something like:
int MyClass::myMemb er = 123;
but for complicated non-POD types, such as a std::vector, how do I
initialize it by
push_back() many elements into it? You see my problem? Thanks.
One way is to use a (static, possibly member) function to initialise your
variable:

// foo.hpp

#ifndef FOO_HPP
#define FOO_HPP

#include <vector>

class Foo
{
public:
static std::vector<int static_member;

static void static_initiali ser(const int z);

Foo();

double y;
};

#endif

// foo.cpp

#include "foo.hpp"

#include <iostream>

std::vector<int Foo::static_mem ber;

void Foo::static_ini tialiser(const int n)
{
std::cout << "Foo::static_in itialiser()" << std::endl;
for (int i=0; i<n; ++i) static_member.p ush_back(i*i);
}

Foo::Foo()
{
std::cout << "Foo::Foo() " << std::endl;
}

// main.cpp

#include "foo.hpp"

#include <iostream>

int main()
{
const int n = 4;

Foo::static_ini tialiser(n);

Foo foo;

for (int i=0; i<n; ++i) std::cout << Foo::static_mem ber[i] << '\n';

return 0;
}

// output

Foo::static_ini tialiser()
Foo::Foo()
0
1
4
9

Note that this won't work if Foo::static_mem ber has to be const. To
handle that situation you can still use a static initialiser function,
but it must return the value you want assigned to your static member.

--
Lionel B
Jul 15 '08 #3
On Tue, 15 Jul 2008 06:54:33 -0700, Steven Woody wrote:
We must did the
following work in C for many many times:

// file: foo.c

static const int my_magic_code_t able [] {
1,
9,
103,
2,
...
};

Now I sure you see what I was looking for is just a equivalent of above
in C++ as simple as we can approach.
Doh! Why didn't you just say that in the first place?

// foo.hpp:

class Foo
{
private:
static const int my_magic_code_t able[];
public:
static const std::vector<int my_magic_code_v ector;
};

// foo.cpp:

const int Foo::my_magic_c ode_table[] =
{
1,
9,
103,
2
};

const std::vector<int Foo::my_magic_c ode_vector(
Foo::my_magic_c ode_table,
Foo::my_magic_c ode_table + sizeof(Foo::my_ magic_code_tabl e)/sizeof(int)
);

Although I'm not sure why you'd want a vector at all here

--
Lionel B
Jul 15 '08 #4
On Jul 15, 10:47 pm, Lionel B <m...@privacy.n etwrote:
On Tue, 15 Jul 2008 06:54:33 -0700, Steven Woody wrote:
We must did the
following work in C for many many times:
// file: foo.c
static const int my_magic_code_t able [] {
1,
9,
103,
2,
...
};
Now I sure you see what I was looking for is just a equivalent of above
in C++ as simple as we can approach.

Doh! Why didn't you just say that in the first place?

// foo.hpp:

class Foo
{
private:
static const int my_magic_code_t able[];
public:
static const std::vector<int my_magic_code_v ector;

};

// foo.cpp:

const int Foo::my_magic_c ode_table[] =
{
1,
9,
103,
2

};

const std::vector<int Foo::my_magic_c ode_vector(
Foo::my_magic_c ode_table,
Foo::my_magic_c ode_table + sizeof(Foo::my_ magic_code_tabl e)/sizeof(int)
);

Although I'm not sure why you'd want a vector at all here
Because what I given is merely an example, I made it to make the
sample code simple so that suitable to post on usenet. In practice,
my table not only contains plain integers, I contains NON-POD objects,
that's one of the reason I choice std::vector. I am looking for a
general solution.
Jul 16 '08 #5
On Jul 15, 5:04 pm, Michael DOUBEZ <michael.dou... @free.frwrote:
Steven Woody a écrit :
[...]
There is still boost.assign:http://www.boost.org/doc/libs/1_35_0...doc/index.html
If I understand correctly (I have never used it), this will give
something like:
const std::vector<int magic_code=list _of(1)(9)(103)( 2)...(42);
If vector<>::push_ back supported chaining, you wouldn't even
need that:

std::vector< int const magic
= std::vector< int >().push_back ( 1 )
.push_back( 9 )... ;

(Of course, in this case, a somewhat shorter name would be
appreciated:-).)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jul 16 '08 #6
On 16 Lug, 13:02, Michael DOUBEZ <michael.dou... @free.frwrote:
James Kanze a écrit :
On Jul 15, 5:04 pm, Michael DOUBEZ <michael.dou... @free.frwrote:
Steven Woody a écrit :
* * [...]
There is still boost.assign:http://www.boost.org/doc/libs/1_35_0...doc/index.html
If I understand correctly (I have never used it), this will give
something like:
const std::vector<int magic_code=list _of(1)(9)(103)( 2)...(42);
If vector<>::push_ back supported chaining, you wouldn't even
need that:

The strcpy(), strcat, str... were designed for chaining but AFAIK, it is
rarely used that way. I guess it would also be marginally useful for
std::vector<>.
* * std::vector< int const magic
* * * * = std::vector< int >().push_back ( 1 )
* * * * * * * * * * * * * * * .push_back(9 )... ;

That's hideous. :)

--
Michael
Hi to all,
I use the following template to trigger static member functions (that
can be used to do any type of initalization ).
It always seemed to work in the few cases I've used it. The only doubt
is the constructor of the template, that refers to the static member
object to enforce instantiation. My doubt is that some compiler
optimization might throw that away. With gcc it never seems to happen
with any optimization.
Any comment?
Regards to all,
Francesco

#include <iostream>
#include <vector>

template< typename T >
class CAutoInitialize r
{
protected:
// enforce sInit instantiation
CAutoInitialize r() { return; sInit; }
private:
struct CInit { CInit() { T::StaticInitia lizer(); } };
static CInit sInit;
};

template< typename T >
typename CAutoInitialize r< T >::CInit CAutoInitialize r< T >::sInit;

//

class CSomething : CAutoInitialize r< CSomething >
{
public:
// avoid static init fiasco
static std::vector< int & GetVec()
{ static std::vector< int sVec; return sVec; }

static void StaticInitializ er()
{
std::cout << "Do anything you want here\n";
GetVec().push_b ack( 10 );
}
};

//

class CSomethingElse : CAutoInitialize r< CSomethingElse >
{
public:
static void StaticInitializ er()
{ std::cout << "Do something else here\n"; }
};

int main()
{
std::cout << "main\n";
CSomething obj1;
CSomethingElse obj2;
std::cin.get();
}

Jul 16 '08 #7
On 16 Lug, 13:42, xtrigger...@gma il.com wrote:
On 16 Lug, 13:02, Michael DOUBEZ <michael.dou... @free.frwrote:


James Kanze a écrit :
On Jul 15, 5:04 pm, Michael DOUBEZ <michael.dou... @free.frwrote:
>Steven Woody a écrit :
* * [...]
>There is still boost.assign:http://www.boost.org/doc/libs/1_35_0...doc/index.html
>If I understand correctly (I have never used it), this will give
>something like:
>const std::vector<int magic_code=list _of(1)(9)(103)( 2)...(42);
If vector<>::push_ back supported chaining, you wouldn't even
need that:
The strcpy(), strcat, str... were designed for chaining but AFAIK, it is
rarely used that way. I guess it would also be marginally useful for
std::vector<>.
* * std::vector< int const magic
* * * * = std::vector< int >().push_back ( 1 )
* * * * * * * * * * * * * * * .push_back( 9 )... ;
That's hideous. :)
--
Michael

Hi to all,
I use the following template to trigger static member functions (that
can be used to do any type of initalization ).
It always seemed to work in the few cases I've used it. The only doubt
is the constructor of the template, that refers to the static member
object to enforce instantiation. My doubt is that some compiler
optimization might throw that away. With gcc it never seems to happen
with any optimization.
Any comment?
Regards to all,
Francesco

#include <iostream>
#include <vector>

template< typename T >
class CAutoInitialize r
{
protected:
* * // enforce sInit instantiation
* * CAutoInitialize r() { return; sInit; }
private:
* * struct CInit { CInit() { T::StaticInitia lizer(); } };
* * static CInit sInit;

};

template< typename T >
typename CAutoInitialize r< T >::CInit CAutoInitialize r< T >::sInit;

//

class CSomething : CAutoInitialize r< CSomething >
{
public:
* * // avoid static init fiasco
* * static std::vector< int & GetVec()
* * { static std::vector< int sVec; return sVec; }

* * static void StaticInitializ er()
* * {
* * * * std::cout << "Do anything you want here\n";
* * * * GetVec().push_b ack( 10 );
* * }

};

//

class CSomethingElse : CAutoInitialize r< CSomethingElse >
{
public:
* * static void StaticInitializ er()
* * { *std::cout << "Do something else here\n"; }

};

int main()
{
* * std::cout << "main\n";
* * CSomething * * *obj1;
* * CSomethingElse *obj2;
* * std::cin.get();

}- Nascondi testo citato

- Mostra testo citato- Nascondi testo citato

- Mostra testo citato

Sorry,
the code I posted is broken if any other statically initialized object
will call GetVec() before the template static object is instantiated.
Fiasco!
The below code is more like it I think, but it's getting
convoluted.. :-(
Moreover it does not address multithreading issues.
Sorry again,
bye,
Francesco
#include <iostream>
#include <vector>

template< typename TDerivingClass, typename TStaticObject >
class CStaticInstance AutoInit
{
public:
static TStaticObject & GetInstance()
{
static bool sInit = TDerivingClass: :StaticInitiali zer();
return GetUnsafe();
}
protected:
static TStaticObject & GetUnsafe()
{
static TStaticObject sObj;
return sObj;
}
CStaticInstance AutoInit() { return; sInit; }
private:
struct CInit { CInit()
{ CStaticInstance AutoInit::GetIn stance(); } };
static CInit sInit;
};

//
template< typename TDerivingClass, typename TStaticObject >
typename CStaticInstance AutoInit< TDerivingClass, TStaticObject
>::CInit
CStaticInstance AutoInit< TDerivingClass, TStaticObject
>::sInit;
//

class CSomething : public CStaticInstance AutoInit< CSomething,
std::vector< int
{
public:
static bool StaticInitializ er( void )
{
std::cout << "init static instance something\n";
GetUnsafe().pus h_back( 13 );
return true;
}
};

//

int main()
{
std::cout << "main\n";
CSomething obj1;
obj1.GetInstanc e();
obj1.GetInstanc e();
std::cin.get();
}
Jul 16 '08 #8
On Jul 16, 1:02 pm, Michael DOUBEZ <michael.dou... @free.frwrote:
James Kanze a écrit :
On Jul 15, 5:04 pm, Michael DOUBEZ <michael.dou... @free.frwrote:
Steven Woody a écrit :
[...]
There is still
boost.assign:http://www.boost.org/doc/libs/1_35_0...doc/index.html
If I understand correctly (I have never used it), this will give
something like:
const std::vector<int magic_code=list _of(1)(9)(103)( 2)...(42);
If vector<>::push_ back supported chaining, you wouldn't even
need that:
The strcpy(), strcat, str... were designed for chaining but
AFAIK, it is rarely used that way.
That's because the return value isn't the one you'd want to
chain.
I guess it would also be marginally useful for std::vector<>.
std::vector< int const magic
= std::vector< int >().push_back ( 1 )
.push_back( 9 )... ;
That's hideous. :)
It's a more or less standard idiom in some OO circles. With
such a long and awkward name, it isn't really very pretty. But
globally, the policy of having all mutators return *this as a
non-const reference can occasionally be useful.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jul 16 '08 #9
On Jul 16, 4:46 pm, James Kanze <james.ka...@gm ail.comwrote:
On Jul 15, 3:54 pm, Steven Woody <narkewo...@gma il.comwrote:
On Jul 15, 9:11 pm, James Kanze <james.ka...@gm ail.comwrote:
On Jul 15, 12:05 pm, Steven Woody <narkewo...@gma il.comwrote:

[...]
Anyway, methods like
td::vector<intN onPOD::foo(SIZE ,4.4)
or
std::vector< int const Class::staticVe ct(
begin( something), end( something) )
simply don't work since they both get too much limitation. What I
need to put into the vector in initial time is very specific data,
filling the vector with many default value or a regular serial is not
enought.

But what is the specific data? If it's known at compile time
(or even if it's not---"something" can be an istream_iterato r),
you can use the second. And if you don't know it until after
entering main, you can't make the vector const.
If all above is what C++ can do for the specific problem, it
is a shame of the language, but I don't believe it can be
true.

Well, I've yet to find a case where the template constructor
taking two iterators wouldn't work (and the data was known
before hand, of course). And you can always use something like:

std::vector< int const Class::staticVe ctor(
someFunctionRet urningAVectorOf Int() ) ;
This seems interesting! I will try right now. And, in my real
program, the elements contained in the std::vector are actually
std::pair objects.
Jul 17 '08 #10

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

Similar topics

3
3605
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...
6
2471
by: lovecreatesbeauty | last post by:
Hello Experts, Why static data members can be declared as the type of class which it belongs to? Inside a class, non-static data members such as pointers and references can be declared as type of its own class. Non-static data members can not be declared as type of its own class (excluding pointers and references).
6
4409
by: Bill Rubin | last post by:
The following code snippet shows that VC++ 7.1 correctly compiles a static member function invocation from an Unrelated class, since this static member function is public. I expected to compile the same invocation from a DistantlyRelated class. What actually happened was that the compiler produced: error C2247: 'A::function' not accessible because 'CloselyRelated' uses 'private' to inherit from 'A' I'm guessing that the above compiler...
11
3841
by: Kevin Prichard | last post by:
Hi all, I've recently been following the object-oriented techiques discussed here and have been testing them for use in a web application. There is problem that I'd like to discuss with you experts. I would like to produce Javascript classes that can be "subclassed" with certain behaviors defined at subclass time. There are plenty of ways to do this through prototyping and other techniques, but these behaviors need to be static and...
4
2554
by: bob | last post by:
Why doesn't c++ let me initialize static members like this: class MySound { static CSoundManager* g_pSoundManager = NULL; };
9
27383
by: subramanian | last post by:
I am a beginner in C++. Suppose I want to build a class: I have given below the starting code: class Date { int day, month, year; static Date default_date; };
4
8361
by: Bram Kuijper | last post by:
Hi all, as a C++ newbie, I got some question on the initialization of static reference data members. Since it isn't possible to initialize static members of a class in the constructor, I should initialize them in advance. However, the following code, in which I first produce two classses and then try to assign a reference of the first class to a static data member of the second class doesn't work. It gives the following compiler error:
4
1981
by: Bram Kuijper | last post by:
Okay, second try (since my posting on 4/27), to find a proper way to initialize a static reference member to an object. I try to initialize a static reference inside the class ga, referencing to an instance of the class bla. According to a previous posting of Zeppe on 4/27... Doing that, this is my code: class bla
5
7237
by: Timothy Madden | last post by:
Hy static members of non-integral type need to be declared in the class, but defined (and constructed or initialized) outside the class. Like this class SystemName { public:
0
8766
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
9291
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...
0
9158
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
8160
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6026
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
4535
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...
2
2698
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2171
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.