473,320 Members | 1,982 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

A Question about initialization...

I have a class that has a static member variable.

string x;

x should never change during use and should be intialized to "abcd".

How does one do this?
Jul 22 '05 #1
19 1913
JustSomeGuy wrote:
I have a class that has a static member variable.

string x;

x should never change during use and should be intialized to "abcd".

How does one do this?


const string x = "abcd";

- Pete
Jul 22 '05 #2
JustSomeGuy wrote:
I have a class that has a static member variable.

string x;

x should never change during use and should be intialized to "abcd".

How does one do this?

For instance:
class X {
public:

static
const std::string str; // declare first.

}; // X

const std::string X::str ( "abcd" ); // initialize later.
Note that, to my great dismay,

class X {
public:

static
const std::string str ( "abcd" ); // in one go? no!

}; // X

does *not* work. Actually, I do not know the reason.
Best

Kai-Uwe
Jul 22 '05 #3
"Pete C." <x@x.x> wrote...
JustSomeGuy wrote:
I have a class that has a static member variable.

string x;

x should never change during use and should be intialized to "abcd".

How does one do this?


const string x = "abcd";


You cannot do this in a class. You're correct that the member has
to be const, but the initialisation should happen in a constructor.

V
Jul 22 '05 #4
"Pete C." <x@x.x> wrote...
JustSomeGuy wrote:
I have a class that has a static member variable.

string x;

x should never change during use and should be intialized to "abcd".

How does one do this?


const string x = "abcd";


The declaration and the definition/initialisation has to be
separate for 'string', if it's a member of a class.

Victor
Jul 22 '05 #5
Victor Bazarov wrote:
"Pete C." <x@x.x> wrote...
JustSomeGuy wrote:
I have a class that has a static member variable.

string x;

x should never change during use and should be intialized to "abcd".

How does one do this?


const string x = "abcd";


You cannot do this in a class. You're correct that the member has
to be const, but the initialisation should happen in a constructor.

V


Ah yes, I didn't notice the "class that has a static member variable" part.
Thanks for pointing it out. :)

- Pete
Jul 22 '05 #6
"Pete C." <x@x.x> wrote...
Victor Bazarov wrote:
"Pete C." <x@x.x> wrote...
JustSomeGuy wrote:
I have a class that has a static member variable.

string x;

x should never change during use and should be intialized to "abcd".

How does one do this?

const string x = "abcd";
You cannot do this in a class. You're correct that the member has
to be const, but the initialisation should happen in a constructor.

V


Ah yes, I didn't notice the "class that has a static member variable"

part. Thanks for pointing it out. :)


Actually, you're very quick to respond, I cancelled that message as soon
as I realised that the member variable JustSomeGuy was asking about was
_static_. For that the declaration has to be in the class, but the
definition and initialisation has to be at the namespace level.

V
Jul 22 '05 #7
Kai-Uwe Bux wrote:

JustSomeGuy wrote:
I have a class that has a static member variable.

string x;

x should never change during use and should be intialized to "abcd".

How does one do this?


For instance:

class X {
public:

static
const std::string str; // declare first.

}; // X

const std::string X::str ( "abcd" ); // initialize later.

Note that, to my great dismay,

class X {
public:

static
const std::string str ( "abcd" ); // in one go? no!

}; // X

does *not* work. Actually, I do not know the reason.


I happened to come across 9.4.2/4 lately. It implies that only const
integral or const enumeration types can be initialised within a class
definition.

Denis
Jul 22 '05 #8
"Denis Remezov" <RE*********************@yahoo.removethis.ca> wrote...
Kai-Uwe Bux wrote:

JustSomeGuy wrote:
I have a class that has a static member variable.

string x;

x should never change during use and should be intialized to "abcd".

How does one do this?


For instance:

class X {
public:

static
const std::string str; // declare first.

}; // X

const std::string X::str ( "abcd" ); // initialize later.

Note that, to my great dismay,

class X {
public:

static
const std::string str ( "abcd" ); // in one go? no!

}; // X

does *not* work. Actually, I do not know the reason.


I happened to come across 9.4.2/4 lately. It implies that only const
integral or const enumeration types can be initialised within a class
definition.


And if you read that part of the Standard carefully, you will see that
there is also one more thing: if the static data member is used outside
the class, it still has to be defined at the namespace level.

Victor
Jul 22 '05 #9
Denis Remezov wrote:
Kai-Uwe Bux wrote:
Note that, to my great dismay,

class X {
public:

static
const std::string str ( "abcd" ); // in one go? no!

}; // X

does *not* work. Actually, I do not know the reason.


I happened to come across 9.4.2/4 lately. It implies that only const
integral or const enumeration types can be initialised within a class
definition.

Denis


Thanks a lot,

that settles it then.

Do you have a guess as what the rational for the provisions of 9.4.2/4
might be? Admittedly, I have not the faintest idea.
Best

Kai-Uwe
Jul 22 '05 #10
I seemed to have asked a provocative question...
Seems to me this should have been a straight forward thing one
would want to do with a language...
Jul 22 '05 #11
Kai-Uwe Bux wrote:

Denis Remezov wrote:
Kai-Uwe Bux wrote:
Note that, to my great dismay,

class X {
public:

static
const std::string str ( "abcd" ); // in one go? no!

}; // X

does *not* work. Actually, I do not know the reason.


I happened to come across 9.4.2/4 lately. It implies that only const
integral or const enumeration types can be initialised within a class
definition.

Denis


Thanks a lot,

that settles it then.

Do you have a guess as what the rational for the provisions of 9.4.2/4
might be? Admittedly, I have not the faintest idea.


[OT & wild speculations]

Just a guess: to make it possible to use integral constants "defined" that
way in integral constant expressions (e.g. array bounds), without the need
for the compiler to look up their values in other translation units (where
they would be eventually defined for real). The utility of non-integral
types is more limited in this respect.

[/OT & wild speculations]

Denis
Jul 22 '05 #12
Kai-Uwe Bux wrote:
Denis Remezov wrote:

Kai-Uwe Bux wrote:
Note that, to my great dismay,

class X {
public:

static
const std::string str ( "abcd" ); // in one go? no!

}; // X

does *not* work. Actually, I do not know the reason.


I happened to come across 9.4.2/4 lately. It implies that only const
integral or const enumeration types can be initialised within a class
definition.

Denis

Thanks a lot,

that settles it then.

Do you have a guess as what the rational for the provisions of 9.4.2/4
might be? Admittedly, I have not the faintest idea.
Best

Kai-Uwe


Allowing integral/enum types to be initialized this way allows you to do
some convenient things. For example, consider the following:

class A
{
static const unsigned N ;
int i[N] ; // error.
public :
} ;
const unsigned A::N = 30 ;
But with this allowance, you could do this, instead:
class A
{
static const unsigned N = 30 ;
int i[N] ; // not an error.
public :
} ;
const unsigned A::N ; // Note that this is still needed if you plan on
using N elsewhere.
Further, creeating a constant integral value doesn't necessarily require
that the program *do* anything. That is, The initialization above
probably doesn't produce any executable code. You can't say the same
about, for example, a std::string, where initialization requires a call
to the constructor.

Alan

Jul 22 '05 #13
Alan Johnson wrote:
Kai-Uwe Bux wrote:
Denis Remezov wrote:

Kai-Uwe Bux wrote:

Note that, to my great dismay,

class X {
public:

static
const std::string str ( "abcd" ); // in one go? no!

}; // X

does *not* work. Actually, I do not know the reason.
I happened to come across 9.4.2/4 lately. It implies that only const
integral or const enumeration types can be initialised within a class
definition.

Denis

Thanks a lot,

that settles it then.

Do you have a guess as what the rational for the provisions of 9.4.2/4
might be? Admittedly, I have not the faintest idea.
Best

Kai-Uwe


Allowing integral/enum types to be initialized this way allows you to do
some convenient things. For example, consider the following:

class A
{
static const unsigned N ;
int i[N] ; // error.
public :
} ;
const unsigned A::N = 30 ;
But with this allowance, you could do this, instead:
class A
{
static const unsigned N = 30 ;
int i[N] ; // not an error.
public :
} ;
const unsigned A::N ; // Note that this is still needed if you plan on
using N elsewhere.
Further, creeating a constant integral value doesn't necessarily require
that the program *do* anything. That is, The initialization above
probably doesn't produce any executable code. You can't say the same
about, for example, a std::string, where initialization requires a call
to the constructor.

Alan

Thanks for the explanation,
I am reading the provision of the standard not as an allowance, though,
but as an restriction. I dislike the need to initialize non-integer/enum
constants far away from their definition. Do you know how the fact
that a constructor might get called relates to where in my source I put
the initialization?
Thanks again

Kai-Uwe
Jul 22 '05 #14
Kai-Uwe Bux wrote:
Alan Johnson wrote:

Kai-Uwe Bux wrote:
Denis Remezov wrote:

Kai-Uwe Bux wrote:
>Note that, to my great dismay,
>
>class X {
>public:
>
> static
> const std::string str ( "abcd" ); // in one go? no!
>
>}; // X
>
>does *not* work. Actually, I do not know the reason.
>

I happened to come across 9.4.2/4 lately. It implies that only const
integral or const enumeration types can be initialised within a class
definition.

Denis
Thanks a lot,

that settles it then.

Do you have a guess as what the rational for the provisions of 9.4.2/4
might be? Admittedly, I have not the faintest idea.
Best

Kai-Uwe


Allowing integral/enum types to be initialized this way allows you to do
some convenient things. For example, consider the following:

class A
{
static const unsigned N ;
int i[N] ; // error.
public :
} ;
const unsigned A::N = 30 ;
But with this allowance, you could do this, instead:
class A
{
static const unsigned N = 30 ;
int i[N] ; // not an error.
public :
} ;
const unsigned A::N ; // Note that this is still needed if you plan on
using N elsewhere.
Further, creeating a constant integral value doesn't necessarily require
that the program *do* anything. That is, The initialization above
probably doesn't produce any executable code. You can't say the same
about, for example, a std::string, where initialization requires a call
to the constructor.

Alan


Thanks for the explanation,
I am reading the provision of the standard not as an allowance, though,
but as an restriction. I dislike the need to initialize non-integer/enum
constants far away from their definition. Do you know how the fact
that a constructor might get called relates to where in my source I put
the initialization?
Thanks again

Kai-Uwe


It may help understanding if we pretend to be a compiler (or rather, it
will help me to try to explain it. Please don't get the impression that
I am attempting to insult your ability to understand). As as compiler,
I rarely see a full picture of what is going on. Instead I just see
what is going on within the translation unit I am currently compiling.
So, let's say I'm compiling and encounter the following :

class C
{
static const std::string test("test") ;
} ;

Assuming this were allowed, and did the obvious thing, I only really
have one sensible choice about what to do. I reserve space for the
std::string option (in whatever manner I go about doing things like
that), and generate a call to std::string's constructor, and place it in
whatever place I normally put code that initializes static objects.

Now, let's say that was in a header file, as class declarations often
are. It is quite likely that I'll encounter that same thing again,
reserve more space for it, and generate another call to the constructor,
because how am I to know that that has already been done? But now I've
already violated the definition of a static class member, which is that
there is only one of them. Not to mention, the linker won't know what
to do with multiple symbols called C::test, and will probably spit out a
"multiply defined" error, or something similar.

Why do integral types not have the same problem? For integral types, the
compiler could just treat every subsequent place in which that
constant's value is needed as a literal with that value, much like a
#define (or it could do something much fancier. I really have no clue
what any actual implementations do).

So what is the "proper" place to put initializations of static members?
My opinion on this is that they should go in the same place as the
definitions for the member functions. That is, if you declare "class C"
in C.h, and implement it in C.cpp, then initialization of static members
should go in C.cpp (probably at the very top).

Alan
Jul 22 '05 #15

"Kai-Uwe Bux" <jk********@gmx.net> wrote in message news:ca**********@news01.cit.cornell.edu...
For instance:
class X {
public:

static
const std::string str; // declare first.

}; // X

const std::string X::str ( "abcd" ); // initialize later.


Initialize it in the initializer list of the ctor.

X::X() : str("abcd") {}
Jul 22 '05 #16
"Duane Hebert" <sp**@flarn2.com> wrote...

"Kai-Uwe Bux" <jk********@gmx.net> wrote in message

news:ca**********@news01.cit.cornell.edu...
For instance:
class X {
public:

static
const std::string str; // declare first.

}; // X

const std::string X::str ( "abcd" ); // initialize later.


Initialize it in the initializer list of the ctor.

X::X() : str("abcd") {}

It's a _static_ data member, did you miss that bit?
Jul 22 '05 #17

"Victor Bazarov" <v.********@comAcast.net> wrote in message news:1VDyc.73966$3x.26101@attbi_s54...
"Duane Hebert" <sp**@flarn2.com> wrote...

"Kai-Uwe Bux" <jk********@gmx.net> wrote in message

news:ca**********@news01.cit.cornell.edu...
For instance:
class X {
public:

static
const std::string str; // declare first.

}; // X

const std::string X::str ( "abcd" ); // initialize later.


Initialize it in the initializer list of the ctor.

X::X() : str("abcd") {}

It's a _static_ data member, did you miss that bit?


Yep.
Jul 22 '05 #18
On Thu, 10 Jun 2004 03:04:11 GMT, "JustSomeGuy" <no**@nottelling.com>
did courageously avow:
I seemed to have asked a provocative question...
Seems to me this should have been a straight forward thing one
would want to do with a language...

I'm not so sure about what everyone else is saying but, my take would
be that if you know the value of the string now and it is not supplied
as part of the instantiation it would make sense to define it at the
same time it is declared:

class X
{
private:
const static char * = "abcd";

...
};

If it is dynamic I'm not sure how it would eventually work out but I
would attempt to use initialization with the constructor rather than
assignment:

class X
{
private static char * myString;

...
};

X::X(const char * s = "abcd") : myString(s)
{
}

I'm still much of a novice, but I can tell you that the following
won't work (at least it doesn't with Visual C++ 6.0). This last
example is frustrating because it actually appears in an academic text
I am studying right now.

class X
{
private char myString[20];

...
};

X:X(const char * s = "abcd") : myString(s)
{
}

This fails with the following error "X::myString : cannot specify
explicit initializer for arrays."
Ken Wilson
"Just because people don't understand you doesn't mean
you are an artist"
Jul 22 '05 #19

"Rick N. Backer" <ke********@NsOhSaPw.cAaM> wrote in message
news:fn********************************@4ax.com...
On Thu, 10 Jun 2004 03:04:11 GMT, "JustSomeGuy" <no**@nottelling.com>
did courageously avow:
I seemed to have asked a provocative question...
Seems to me this should have been a straight forward thing one
would want to do with a language...

I'm not so sure about what everyone else is saying but, my take would
be that if you know the value of the string now and it is not supplied
as part of the instantiation it would make sense to define it at the
same time it is declared:

class X
{
private:
const static char * = "abcd";

...
};

If it is dynamic I'm not sure how it would eventually work out but I
would attempt to use initialization with the constructor rather than
assignment:

class X
{
private static char * myString;

...
};

X::X(const char * s = "abcd") : myString(s)
{
}

I'm still much of a novice, but I can tell you that the following
won't work (at least it doesn't with Visual C++ 6.0). This last
example is frustrating because it actually appears in an academic text
I am studying right now.

class X
{
private char myString[20];

...
};

X:X(const char * s = "abcd") : myString(s)
{
}

This fails with the following error "X::myString : cannot specify
explicit initializer for arrays."
Ken Wilson
"Just because people don't understand you doesn't mean
you are an artist"

I'm not sure but I get the feeling you're impression of static
is that of a C programmer... Static has a different meaning in C++
(I of course am just assuming)

Jul 22 '05 #20

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

Similar topics

14
by: Fred H | last post by:
I'm reading a STL book right now, and there I've picked up the folowing syntax: class C { private: int value; public: C(int initValue) : value(initValue) { } }
111
by: JKop | last post by:
Okay here we go, I feel it's about time people conversed about the bullshit aspects of C++ (including the bullshit stuff brought forward from C). I'll begin with a few of my own grievances: 1)...
3
by: Tran Tuan Anh | last post by:
Dear all, I am new with C++ and very confused with some features. Really appreciate if you can explain to me some of stuffs below. I define a class: class A { static A* instance = 0; };
42
by: kiplring | last post by:
1. int intArr = new int; 2. int intArr = new int; rgnNumberArr.Initialize(); 3. int intArr = new int; for( int i=0; i<intArr .lenght; i++)
4
by: Magcialking | last post by:
here an example from <<c++primer(3rd edition)>>: template<class elemtype> void Array<elemtype>::grow(){ elemtype *oldia=_ia; int oldsize=_size; _size=size+size/2+1; _ia=new elemtype; int...
4
by: Jess | last post by:
Hello, I tried several books to find out the details of object initialization. Unfortunately, I'm still confused by two specific concepts, namely default-initialization and...
2
by: timlyee | last post by:
int *p = new int; auto_ptr<intap1 = p; //will fail on 3 1 auto_ptr<intap1(p); //ok 2 *ap1 = 12; // 3 the first situation has called :...
17
by: Jess | last post by:
Hello, If I have a class that has virtual but non-pure declarations, like class A{ virtual void f(); }; Then is A still an abstract class? Do I have to have "virtual void f() = 0;"...
13
by: WaterWalk | last post by:
Hello. When I consult the ISO C++ standard, I notice that in paragraph 3.6.2.1, the standard states: "Objects with static storage duration shall be zero-initialized before any other...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.