Defining constants in classes

J

Joe

This is a very basic question, but why can't I do the following ?

class schedule {

private:
static const string mScheduleFile = "schedule.txt";
....
}


I hope it is clear what I am trying to do. In the member functions, I then
want to "fout.open(mScheduleFile)".
Is there way of doing this that actually works?

TIA,
Joe.
 
J

Jonathan Turkanis

Joe said:
This is a very basic question, but why can't I do the following ?

class schedule {

private:
static const string mScheduleFile = "schedule.txt";
...
}

The language rules only permit in-class initialization of static const
members of integral type.

You can get the effect you're after with a static member function
returning a string or string literal, like so:

const std::string& schedule_file()
{
static const std::string file("schedule.txt");
return file;
}

or

const char* schedule_file()
{
static const char* file = "schedule.txt";
return file;
}


Jonathan
 
A

Alf P. Steinbach

* "Jonathan Turkanis said:
The language rules only permit in-class initialization of static const
members of integral type.

Yes, but the OP asked why.

The answer to that seems to be "nobody knows why".

The language just turned out that way through historic accidents etc.



You can get the effect you're after with a static member function
returning a string or string literal, like so:

const std::string& schedule_file()
{
static const std::string file("schedule.txt");
return file;
}

or

const char* schedule_file()
{
static const char* file = "schedule.txt";
return file;
}

Or the constant can be defined in the class implementation file:


============ Schedule.hpp =============

#ifndef SCHEDULE_H
#include <string>

class Schedule
{
private:
static std::string const mScheduleFile;
};
#endif


============ Schedule.cpp =============

#include <Schedule.hpp>

std::string const Schedule::mScheduleFile = "schedule.txt";
 
J

Joe

Thanks for the quick reply. That works fine, but I can't help feeling it
makes things a a little "untidy".

Is that a standard solution to a standard problem?
Or am I going about the whole problem in an unusual/bad way?

Joe.
 
J

Joe

Joe said:
Thanks for the quick reply. That works fine, but I can't help feeling it
makes things a a little "untidy".

Is that a standard solution to a standard problem?
Or am I going about the whole problem in an unusual/bad way?

Joe.

Sorry for the top-post!!

(I have never understood why that is a big deal - it makes life so much
faster if you don't have to scroll, especially for a short post like this.
If anyone has a good reason for why people don't like it, can they tell me?
I will sleep better if I know)

Joe.
 
J

Jonathan Turkanis

Joe said:
Thanks for the quick reply. That works fine, but I can't help feeling it
makes things a a little "untidy".

Is that a standard solution to a standard problem?
Or am I going about the whole problem in an unusual/bad way?

It's one standard solution. Alf gave another one. I think they're both
a bit untidy.

I tend to use the one I showed you because I write a lot of
header-only libraries.

(I' not against top-posting, as such. I think it's like always driving
on the right or left side of the road; it doesn't matter as long as
everyone does the same thing. ;-) )

Jonathan
 
P

Pete Becker

Alf P. Steinbach said:
Yes, but the OP asked why.

The answer to that seems to be "nobody knows why".

The language just turned out that way through historic accidents etc.

The reason is that in-class initialization of static const members was
added in order to support their use as compile-time constants. Arrays of
char, floats, etc. can't be used as compile-time constants, so can't be
initialized in this way.
 
J

Julie

Joe said:
Sorry for the top-post!!

(I have never understood why that is a big deal - it makes life so much
faster if you don't have to scroll, especially for a short post like this.
If anyone has a good reason for why people don't like it, can they tell me?
I will sleep better if I know)

Joe.

I agree 100%. I finally caved in, not because of the people that kept harping
on me, but because it is part of the newsgroup FAQ. Makes about as much sense
to me as arguing about indentation and brace placement... NNTP is definitely
an outdated protocol.
 
A

Alf P. Steinbach

* Pete Becker said:
The reason is that in-class initialization of static const members was
added in order to support their use as compile-time constants.

Yes, the usefulness of compile-time constants was probably the reason
why they were allowed in this context.

Arrays of
char, floats, etc. can't be used as compile-time constants, so can't be
initialized in this way.

Nope, that does not explain why other constants are not allowed. I very
much doubt that GodAllah appeared in some committee meeting and declared
"Constants That Cannot Be Used As Compile Time Constants Are So Inherently
Evil That You Must Make Them More Difficult To Use". Instead, it seems
much more plausible that the committee used a heuristic on the lines of
"add only that which is absolutely critical, _or_ championed by VIP's".
 
P

Pete Becker

Alf P. Steinbach said:
Yes, the usefulness of compile-time constants was probably the reason
why they were allowed in this context.

It's not probably the reason. It is the reason.
Nope, that does not explain why other constants are not allowed. I very
much doubt that GodAllah appeared in some committee meeting and declared
"Constants That Cannot Be Used As Compile Time Constants Are So Inherently
Evil That You Must Make Them More Difficult To Use". Instead, it seems
much more plausible that the committee used a heuristic on the lines of
"add only that which is absolutely critical, _or_ championed by VIP's".

Phrase it however you like. Regardless, no historic [sic] accidents etc.
 
J

Jon Bell

[snippety snippety snip]
Sorry for the top-post!!

(I have never understood why that is a big deal - it makes life so much
faster if you don't have to scroll, especially for a short post like this.

It makes life so much faster for the people who read your postings if you
*delete* quoted material that isn't immediately relevant to your response.
Then people neither have to scroll through it, nor wait for it to
download. People who actually want to read the entire preceding posting
can usually fetch it easily from their news server. (for example, all I
have to do is hit the back-arrow key.)
 
A

Alf P. Steinbach

* Pete Becker said:
Alf P. Steinbach said:
Yes, the usefulness of compile-time constants was probably the reason
why they were allowed in this context.

It's not probably the reason. It is the reason.
Nope, that does not explain why other constants are not allowed. I very
much doubt that GodAllah appeared in some committee meeting and declared
"Constants That Cannot Be Used As Compile Time Constants Are So Inherently
Evil That You Must Make Them More Difficult To Use". Instead, it seems
much more plausible that the committee used a heuristic on the lines of
"add only that which is absolutely critical, _or_ championed by VIP's".

Phrase it however you like. Regardless, no historic [sic] accidents etc.

If you have any evidence that there was some informed, well-considered
decision to disallow e.g.


struct X
{
static double const = 1.23;
};

and

struct Y
{
static char const s[] = "disallowed for Very Good Reasons";
};

then I as well as the OP and many others would like to know the reason(s).

So spit it out, don't be shy, don't beat about the bush with incoherent
mumblings about "no historic [sic] accident" and so forth.

What, in your opinion or knowledge, makes a double value incredibly more
difficult or hazard-prone or whatever than e.g. a bool or int in struct X,
and what makes the compiler unable to translate the declaration in Y to

struct Z
{
static char const s[];
};

char const Z::s[] = "allowed for Very Good Reasons";

?
 
R

Rob Williscroft

Joe wrote in
This is a very basic question, but why can't I do the following ?

class schedule {

private:
static const string mScheduleFile = "schedule.txt";
...
}


I hope it is clear what I am trying to do. In the member functions, I
then want to "fout.open(mScheduleFile)".
Is there way of doing this that actually works?

You might think you would saved some typeing if this was allowed,
but unless mScheduleFile is only used as a compile-time constant
(which is imposible, see Note below) you would also need a defenition:

struct X
{
/* declaration and initializer (not a defenition)
*/
static int const value = 10;
};

/* this is ok it compile-time usage
*/
char array[ X::value ];

/* This however requires a defenition for X::value
*/
int get_value()
{
return X::value;
}

/* A more obvious case
*/
int const &get_ref()
{
return X::value;
}

The defenition for X::value looks like this:

int const X::value;

and must (according to the Standard) appear in one and only one
translation unit (aka TU, usually a .cpp file).

Note that the only type of compile-time constant that C++ supports
are intergral ones, not float, char [], char * or std::string.

So for in class initialization of non-intergral constants to have
any value we first need to eliminate the language rule that requires
the out of class defenition.

Rob.
 
D

Dietmar Kuehl

Joe said:
(I have never understood why that is a big deal - it makes life so much
faster if you don't have to scroll, especially for a short post like this.

Normally, for short replies you need only a short context either. Thus,
there is not much scrolling needed anyway. The only reason to quote
something is to setup a context. Thus, why quote if you don't want people
to read it *before* reading your statements on the issue. There is a
signature around which actually brings it to the point quite well but I
don't have the exact wording. It goes something like this:

A: it makes reading things harder
Q: why is top posting bad?
If anyone has a good reason for why people don't like it, can they tell me?
I will sleep better if I know)

Well, if you top posted, you might actually sleep worse: excessive quoting
is a copyright infringement! Every article is covered by an implicit
copyright which protects the author's rights. Readers are allowed to read
things, make reasonable quotes (this is always allowed and cannot really
be prohibited as far as I know), and that's about it. Quoting texts entirely
or adding only minor own stuff to an article is generally prohibited. As is,
BTW, using any code posted in articles! Of course, more liberal copyrights
can be given at the author's discretion. I think the implicit copyright, ie.
the one given if the author does not state anything explicitly, is basically
as restrictive as a copyright can become. Note, that the copyright
legislation is international law. Also note that I'm not a lawyer: this is
what I understood from reading some stuff on copyright issues. However, I'm
pretty sure that at least the gist is right even if some details are wrong.

The issue of top-posting came up in a discussion amoung the moderators of
comp.lang.c++.moderated these days, too, although embedded into the bigger
context of overquotes. Our current policy is effectively to reject articles
on the basis of overquotes if the ratio between new material and quotes is
too bad and there seems to be no reason for that much quoting. The ratio is
an objective measure while the evaluation of whether the quoting is really
necessary is subjective, of course. Most rejections due to overquoting are
due to articles using top posting although we don't reject top posts per
se. I think there is a consensus amoung the moderators to continue rejecting
articles due to overquoting.
 
S

Stewart Gordon

Joe said:
This is a very basic question, but why can't I do the following ?

class schedule {

private:
static const string mScheduleFile = "schedule.txt";
...
}

I hope it is clear what I am trying to do. In the member functions, I then
want to "fout.open(mScheduleFile)".
Is there way of doing this that actually works?

Yes.

class schedule {

private:
static const string mScheduleFile;
};

const string schedule::mScheduleFile("schedule.txt");
 
J

Julie

Well, if you top posted, you might actually sleep worse: excessive quoting
is a copyright infringement!

Never heard that one. I'd wait for a court ruling on that one, or at the very
least authoritive commentary from a copyright lawyer. I *HIGHLY* doubt that
there is any basis for copyright infringement as the OP should assume that
their comments are released into the public domain when posting to a public
forum. Again, my comments have just as much (or lack of) validity as yours --
the courts would have to rule on that one.
The issue of top-posting came up in a discussion amoung the moderators of
comp.lang.c++.moderated these days, too, although embedded into the bigger
context of overquotes. Our current policy is effectively to reject articles
on the basis of overquotes if the ratio between new material and quotes is
too bad and there seems to be no reason for that much quoting.

As I said previously, NNTP is an outdated (and severely insufficient)
protocol. It needs to be expanded to add new required features such as the
ability to separate replies from new comments, and that would allow newsreaders
the ability to let the user decide how previous comments would be displayed:
top, bottom, not at all... Unfortunately, we are stuck w/ what we have now,
and find that such trivial issues regarding posting are cause to limit the
valid dialog on a subject.
 
C

Claudio Puviani

Alf P. Steinbach said:
If you have any evidence that there was some informed, well-considered
decision to disallow e.g.


struct X
{
static double const = 1.23;
};

and

struct Y
{
static char const s[] = "disallowed for Very Good Reasons";
};

then I as well as the OP and many others would like to know the reason(s).

It's very simple: in what compilation unit would the variable 'Y::s' be stored?
If the variable is defined in the class definition, the compiler/linker have to
somehow collaborate to avoid redundant definitions. By forcing static data
members to be defined outside of the class, the decision falls on the programmer
and not on some extension of the linker.

One can argue that the problem is already being addressed for templates, but
there, it's a necessity. With static data members, it would amount to nothing
more than syntactic sugar.

Claudio Puviani
 
A

Alf P. Steinbach

* Julie said:
I *HIGHLY* doubt that there is any basis for copyright infringement

I agree. Here Dietmar seems to be a victim of group thinking within the
clc++m moderator cliche. But since those guys are generally intelligent ones
it is perhaps more plausible that this is meant as irony. Difficult to tell,
these days. We have to use the American way now: "Note: above is irony".


As I said previously, NNTP is an outdated (and severely insufficient)
protocol. It needs to be expanded to add new required features such as the
ability to separate replies from new comments, and that would allow newsreaders
the ability to let the user decide how previous comments would be displayed:
top, bottom, not at all... Unfortunately, we are stuck w/ what we have now,
and find that such trivial issues regarding posting are cause to limit the
valid dialog on a subject.

There is currently no way to infer automatically what the poster intends and
wants to convey to the reader.

Hence, it seems you've overstuffed yourself on Microsoft marketing, Julia.

I don't think it is a coincidence that you're both arguing for top-posting and
dragging in baby/manager-level Microsoft marketing -- for the "official"
definition of top-posting explicitly mentions Microsoft, idiot and newbie.
 
A

Alf P. Steinbach

* "Claudio Puviani said:
Alf P. Steinbach said:
If you have any evidence that there was some informed, well-considered
decision to disallow e.g.


struct X
{
static double const = 1.23;
};

and

struct Y
{
static char const s[] = "disallowed for Very Good Reasons";
};

then I as well as the OP and many others would like to know the reason(s).

It's very simple: in what compilation unit would the variable 'Y::s' be stored?

As with other namespace-level constants like


const char s[] = "a constant";


If the variable is defined in the class definition, the compiler/linker have to
somehow collaborate to avoid redundant definitions.

That's somehow already the case for other constructs, including all
inline functions.

E.g., in

struct S
{
double x, y;

void mult( double s ){ x *= s; y *= s; }
};

the compiler and linker have to somehow collaborate on the definition of
function 'mult'.

Somehow that is not a problem at all.


By forcing static data
members to be defined outside of the class, the decision falls on the programmer
and not on some extension of the linker.

Do you think there was a decision to disallow certain constructs in
order to force the programmers to make decisions?

That, instead of the committee _not_ making a decision, they did make a
decision to force the programmers to have to make needless decisions?

I sincerely doubt that.



One can argue that the problem is already being addressed for templates, but
there, it's a necessity. With static data members, it would amount to nothing
more than syntactic sugar.

Do you think this would entail less efficient compilation and
linking, then?
 
D

Default User

Julie said:
Never heard that one. I'd wait for a court ruling on that one, or at the very
least authoritive commentary from a copyright lawyer. I *HIGHLY* doubt that
there is any basis for copyright infringement as the OP should assume that
their comments are released into the public domain when posting to a public
forum. Again, my comments have just as much (or lack of) validity as yours --
the courts would have to rule on that one.

That's not true at all. Where did you get such an idea? The only way to
have something enter the public domain is for the copyright to expire
(which takes a long time) or for the copyright holder to explicitly
place it into the public domain.



Brian Rodenborn
 

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

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top