Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Initialization of static member variables in classes.

31 views
Skip to first unread message

Paul

unread,
Sep 1, 2015, 5:24:54 AM9/1/15
to
I understand that, for many years (since about 03 perhaps), it's been fine to write

class SomeClass
{//
const static int x = 3;
//
};

More recently, (C++ 09 I think) we have been able to write

class SomeClass
{
//
int x = 3;
//

};

What I haven't been able to find out is what happens if the member variable is static and non-constant?

Can we write the below?

Thank you,

Paul

class SomeClass
{
//
static int x = 3;
//

};

Richard

unread,
Sep 1, 2015, 3:09:04 PM9/1/15
to
[Please do not mail me a copy of your followup]

Paul <peps...@gmail.com> spake the secret code
<25300220-65b5-4545...@googlegroups.com> thusly:

>What I haven't been able to find out is what happens if the member
>variable is static and non-constant?

As I understand it, it is a shorthand for initializing non-static
members of a class.

>Can we write the below?

shell 179> g++ -std=c++0x /tmp/a.cpp
/tmp/a.cpp:7:17: error: ISO C++ forbids in-class initialization of
non-const static member 'SomeClass::x'
static int x = 3;
^
shell 180> cat /tmp/a.cpp
#include <cassert>

class SomeClass
{
public:
//
static int x = 3;
//

};

int main()
{
assert(SomeClass::x == 3);
SomeClass s;
assert(SomeClass::x == 3);
return 0;
}

--
"The Direct3D Graphics Pipeline" free book <http://tinyurl.com/d3d-pipeline>
The Computer Graphics Museum <http://computergraphicsmuseum.org>
The Terminals Wiki <http://terminals.classiccmp.org>
Legalize Adulthood! (my blog) <http://legalizeadulthood.wordpress.com>

Richard Damon

unread,
Sep 1, 2015, 8:45:11 PM9/1/15
to
I think the issue is that for non-const static members, the compiler
needs to know where to place the memory definition (what object module
contains the definition). For static const, this isn't an issue, as the
compiler doesn't actually need to create a memory object, it can just
always use the constant.

For non-static members, it just knows to add the initialization to all
constructors.

Due to templates and inline functions, the compiler needs to have
mechanisms to handle this sort of stuff, but maybe this case predates
those requirements and was never added.
0 new messages