473,561 Members | 3,564 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

best way to initialize static member objects

I have class with two static member objects, one of type int and one
of type vector<int>.

static int myStaticMemberI nt
static vector<int> myStaticMemberV ector;

I know how to initialize the int member:

MyClass::myStat icMemberInt = 99;

But what is the best way to initialzie myStaticMemberV ector?

In particular, the initialization code I want to use is somewhat
complex, and involves processing a series of strings to come up with
each int value for the vector. I'd appreciate any ideas on how to
solve this problem.

Thanks,
cpp
Jul 22 '05 #1
15 2853

Cpp,

Can you put all this stuff into another static object which can perform your
special initialization of the vector ? That is to say, in the constructor
for the
"mother" object, you can perform some complex C++ to compute the initial
values of the vector.

Alternatively, you could do something like

static vector<int> myStaticMemberV ector = foobar();

where foobar is a function returning a vector<int> value which performs
your
necessary setup. I was thinking foobar() would be a free function or static
function
of the class, but I guess it could be a object member function . A variation
on this would
be foobar( string stringarray[]) if the strings involved in the computation
are known at
compile time or can be statically determined.

There might be a few snags in this approach, for instance, the question of
the IO channels
for the program being open and ready to read from the outside, without
knowing a bit more
about your program, I can't say.

dave
"cppaddict" <he***@hello.co m> wrote in message
news:ts******** *************** *********@4ax.c om...
I have class with two static member objects, one of type int and one
of type vector<int>.

static int myStaticMemberI nt
static vector<int> myStaticMemberV ector;

I know how to initialize the int member:

MyClass::myStat icMemberInt = 99;

But what is the best way to initialzie myStaticMemberV ector?

In particular, the initialization code I want to use is somewhat
complex, and involves processing a series of strings to come up with
each int value for the vector. I'd appreciate any ideas on how to
solve this problem.

Thanks,
cpp

Jul 22 '05 #2

"cppaddict" <he***@hello.co m> wrote in message
news:ts******** *************** *********@4ax.c om...
I have class with two static member objects, one of type int and one
of type vector<int>.

static int myStaticMemberI nt
static vector<int> myStaticMemberV ector;

I know how to initialize the int member:

MyClass::myStat icMemberInt = 99;

But what is the best way to initialzie myStaticMemberV ector?

In particular, the initialization code I want to use is somewhat
complex, and involves processing a series of strings to come up with
each int value for the vector. I'd appreciate any ideas on how to
solve this problem.

Thanks,
cpp


This is just off the top of my head, there are probably better ways (such as
not using statics if you can avoid it!). But what about a function
returning the initialized vector, such as

typedef std::vector<int > int_vector;

extern int_vector init_vector();

static int_vector my_vector = init_vector();

Not efficient in that there is a lot of data movement (unless the compiler
is smart enough to optimize it away), it should work. If that is a problem,
then maybe:

extern int init_vector(int _vector& v);

static int_vector my_vector;
static int temp = init_vector(my_ vector);

Jul 22 '05 #3
cppaddict posted:
I have class with two static member objects, one of type int and one
of type vector<int>.

static int myStaticMemberI nt
static vector<int> myStaticMemberV ector;

I know how to initialize the int member:

MyClass::myStat icMemberInt = 99;

But what is the best way to initialzie myStaticMemberV ector?

In particular, the initialization code I want to use is somewhat
complex, and involves processing a series of strings to come up with
each int value for the vector. I'd appreciate any ideas on how to
solve this problem.

Thanks,
cpp

Make a class out of the static variable and give it an constructor! One way.

-JKop
Jul 22 '05 #4
This is just off the top of my head, there are probably better ways (such as
not using statics if you can avoid it!).


Xenos,

What's wrong with static member data? I've never heard anything to
that effect before.

Thanks,
cpp
Jul 22 '05 #5
Alternativel y, you could do something like

static vector<int> myStaticMemberV ector = foobar();

where foobar is a function returning a vector<int> value which performs
your
necessary setup. I was thinking foobar() would be a free function or static
function
of the class, but I guess it could be a object member function . A variation
on this would
be foobar( string stringarray[]) if the strings involved in the computation
are known at
compile time or can be statically determined.


I think one of these methods will do what i want.

thanks for your help,
cpp
Jul 22 '05 #6
On Wed, 12 May 2004 20:32:56 GMT, cppaddict <he***@hello.co m> wrote:
I have class with two static member objects, one of type int and one
of type vector<int>.

static int myStaticMemberI nt
static vector<int> myStaticMemberV ector;

I know how to initialize the int member:

MyClass::mySta ticMemberInt = 99;

But what is the best way to initialzie myStaticMemberV ector?

In particular, the initialization code I want to use is somewhat
complex, and involves processing a series of strings to come up with
each int value for the vector. I'd appreciate any ideas on how to
solve this problem.

Thanks,
cpp


How about making access to the vector be via a static member function,
rather than providing direct access to the vector? That way you can have
the function do initialization the first time it is called. In the
following example, I manipulate the vector through a pointer in main, so I
can re-use the pointer in multiple calls to the static function (which I've
named the same as you named your vector.). The syntax would be cleaner,
though, if I simply used a reference instead of the pointer. But the
implementation of the class and member function would remain the same.

Note also that this example provides no protection for the vector itself;
it may as well be public. To control client operations, you can provide
the usual interface functions (overloaded const and con-const subscript
operators, for example), make myStaticMemberV ector() private, and have your
interface functions internally call the static function to get the
initialization behavior you want...

#include <iostream>
#include <vector>

class T
{
public:
static std::vector<int > &myStaticMember Vector();
private:
static int myStaticMemberI nt; // = whatever;
static std::vector<int > vector_;
};

std::vector<int > T::vector_;

std::vector<int > &T::myStaticMem berVector()
{
static bool first_time = true;

if (first_time)
{
vector_.push_ba ck(10);
vector_.push_ba ck(20);
vector_.push_ba ck(30);
vector_.push_ba ck(40);
first_time = false;
}

return vector_;
}

int main()
{
using namespace std;
std::vector<int > *vi = &T::myStaticMem berVector();

for (int i = 0; i < vi->size(); i++)
cout << "vector[" << i << "] = " << (*vi)[i] << endl;
cout << endl;

vi->push_back(50 );
vi = &T::myStaticMem berVector(); // show no init this time

for (int i = 0; i < vi->size(); i++)
cout << "vector[" << i << "] = " << (*vi)[i] << endl;

return 0;
}

Output:

vector[0] = 10
vector[1] = 20
vector[2] = 30
vector[3] = 40

vector[0] = 10
vector[1] = 20
vector[2] = 30
vector[3] = 40
vector[4] = 50

-leor
--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html
Jul 22 '05 #7
Leor,

Thank you very much. That is a nice solution. A couple questions....
To control client operations, you can provide
the usual interface functions (overloaded const and con-const subscript
operators, for example),


what are const and con-const subscript operators?

Also, I know you said using ref variables instead of pointer in main
would be cleaner. I am curious why you did use pointers, because the
code that follows works too.

Thanks again for your help,
cpp

PS: I had to change int i to unsigned int i in the loops b/c the
compiler won't allow you to compare signed and unsigned ints (at least
borland won't)
----WORKING ALTERNATIVE------
int main() {
using namespace std;
std::vector<int > vi = T::myStaticMemb erVector();

for (unsigned int i = 0; i < vi.size(); i++)
cout << "vector[" << i << "] = " << vi[i] << endl;
cout << endl;

vi.push_back(50 );
vi = T::myStaticMemb erVector(); // show no init this time

for (unsigned int i = 0; i < vi.size(); i++)
cout << "vector[" << i << "] = " << vi[i] << endl;

return 0;
}

Jul 22 '05 #8
On Thu, 13 May 2004 01:52:09 GMT, cppaddict <he***@hello.co m> wrote:
Leor,

Thank you very much. That is a nice solution. A couple questions....
To control client operations, you can provide
the usual interface functions (overloaded const and con-const subscript
operators, for example),
what are const and con-const subscript operators?


Well, if you're providing an interface that includes subscripting
operators, you generally need one that's a non-const member function (that
will be fine for applying to non-const objects), and another that's a const
member function (to allow const objects to be subscripted.).

Let's say you're implementing a class named MyVector, holding ints.. The
relevant portions would go something like this (untested code):

class MyVector {
public:
MyVector(...) {...}; // constructor(s)
int &operator[](size_t i) { return a_[i]; }
const int &operator[](size_t i) const { return a_[i]; }
...
private:
int *a_;
size_t size;
};

The idea is that if you have a const MyVector and you subscript it, the
result should be a reference to a const element, and if you have a
non-const MyVector, it should return a reference to a non-const. Const-ness
is important in C++ so that operations applied to function arguments that
have been declared as reference-to-const will be allowed (as long as
they're read-only):

void foo(const MyVector &mv)
{
cout << "The first value in mv is: " << mv[0] << endl;
}

The Above wouldn't compile if only the non-const operator[] were available,
because you can't invoke a non-const member function on a const object. If
you need to assign through the reference (using a non-const MyVector mv):

mv[0] = 10;

then it would use the non-const overload. I've tried to whittle this issue
down to the bare essentials, but it is rather involved ;-)

Also, I know you said using ref variables instead of pointer in main
would be cleaner. I am curious why you did use pointers, because the
code that follows works too.
But not with the same output, I'd wager. I'll explain down below.

Thanks again for your help,
cpp
Glad to help.

PS: I had to change int i to unsigned int i in the loops b/c the
compiler won't allow you to compare signed and unsigned ints (at least
borland won't)
----WORKING ALTERNATIVE------
int main() {
using namespace std;
std::vector<int > vi = T::myStaticMemb erVector();
Above, you're copying an entire vector upon return from the function. After
that, vi has no connection to the vector in the class. They're two separate
vectors.

for (unsigned int i = 0; i < vi.size(); i++)
cout << "vector[" << i << "] = " << vi[i] << endl;
cout << endl;
You wouldn't know that from the output (yet), because your vector vi is a
/copy/ of the one in the class!

vi.push_back(50 );
The above changes your vector, not the one in the class.
vi = T::myStaticMemb erVector(); // show no init this time
And you're now making yet another copy, and replacing the old vi (yours)
with a copy of the vector from the class.

for (unsigned int i = 0; i < vi.size(); i++)
cout << "vector[" << i << "] = " << vi[i] << endl;
You should not be seeing the value 50 when you run it this way. If you
are, I need to go back to C++ school ;-)

Good luck,
-leor

return 0;
}


--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html
Jul 22 '05 #9

But not with the same output, I'd wager. I'll explain down below.

You should not be seeing the value 50 when you run it this way. If you
are, I need to go back to C++ school ;-)


Leor,

Indeed you are right. Thanks again for these explanations. They
cleared up quite a bit for me.

cpp
Jul 22 '05 #10

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

Similar topics

3
1655
by: Bill Sun | last post by:
Hi, I have a question about to initialize a static map member like this: In the mapclass.h; class mapclass { private: static map<string, int> s_mapArray; }
15
5312
by: Geoff Cox | last post by:
Hello, Can I separately declare and initialize a string array? How and where would I do it in the code below? It was created using Visual C++ 2005 Express Beta 2 ... In C# I would have private string myArray;
1
4226
by: philwozza | last post by:
Hi I have a THREAD class that uses the static variable NextThreadID to store the id of the next thread to be created and a static Mutex to protect it. class THREAD { public: int Start(void); private: unsigned int ThreadID;
9
27377
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
8348
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...
18
9092
by: Ehud Shapira | last post by:
Is it possible to have a declaration of a struct pointer initialized to an unnamed struct? (I'm only concerned with static/global variables, if it matters.) I'm trying to do something like: struct st_a { int i, j; };
8
14716
by: aaragon | last post by:
Hi, just a very simple question. I was wondering what is the most efficient way of initializing an array. I have a very simple class that wraps an array to provide bound checking, something like this: enum checkMode {CHECK, NOCHECK}; template <int n, checkMode c = CHECK> struct ArrayStructure { static const short dim_ = n;
9
3400
by: Steven Woody | last post by:
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. -
5
7210
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
7647
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7859
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8088
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...
0
6210
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...
0
3617
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...
0
3600
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2068
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
1181
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
896
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...

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.