static member variables

J

John Ratliff

Do I have to declare store in my implementation file for all static
member variables, even when they are const ints?

In Windows, using msys with g++ 3.4.2 and whatever linker I'm not sure
(probably gnu binutils), I didn't have to declare storage for any of my
static const integer member variables, but in Linux, the linker can't
find four of them. I'm assuming the ones it found were simply replaced
by the compiler and it didn't need to keep them stored. Perhaps the
Windows g++ optimised the storage space away while my Linux g++ (3.3.6)
didn't.

Here is what I want to do:

class foo {
public:
static const int bar = 3;
};

Then I might reference bar somewhere down the line. Can I initialize bar
here in the header file? Do I still need to have

const int foo::bar;

in my implementation (cpp) file?

As I said, I didn't need that const int foo::bar line in Windows under
msys, but Linux isn't liking it. I'm assuming this is an optimization
thing, and I probably needed storage declarations for all my static
variables. Is this right?

Can I still initialize my variables in the class def even if I defined
them in the impl file?

My big problem, and the reason I didn't declare storage space in the
first place is I have something that looks like this:

class foo {
public:
static const int SRAM_FILE_SIZE = 0x2000;
private:
char buffer[SRAM_FILE_SIZE];
};

If I don't declare the value before buffer, it can't use the constant.

Thanks,

--John Ratliff
 
A

AnonMail2005

According to Item #2 in Meyer's Effective C++, Third Edition,
static const integral types are allowed to be initialized at
the point of declaration (i.e. in the .h file).

In some cases compilers that support this may still require
a definition in the cpp file. For example, if you take the
address of the variable. From that item, it is clear that
if initialization is done in the .h file you can't do it in
the .cpp file. But it is not clear if either or is allowed.

Older compilers may not support this so you just need to
define and initialize the variable in the cpp file. For
these older compilers, where you need the const variable's
value further down in the class declaration (e.g. for an
array declaration) Meyer's describes the enum hack:

class A{
enum { Size = 100 };
int Array[Size];
}
 

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,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top