initializing a constant in the .h file?

A

anonymous

hello,
i am attempting to initialize a constant in my .h file. it would be terrific if i
could also assign the constant, but i continue to get compile problems. this
is what i'm trying to do:

(in myfile.h)
const std::string MY_CONSTANT = "permanent value";

but my compiler (gcc version 3.2.1) tells me:

ISO C++ forbids initialization of member

any feedback is appreciated
 
J

John Harrison

hello,
i am attempting to initialize a constant in my .h file. it would be
terrific if i
could also assign the constant, but i continue to get compile problems.
this
is what i'm trying to do:

(in myfile.h)
const std::string MY_CONSTANT = "permanent value";

but my compiler (gcc version 3.2.1) tells me:

ISO C++ forbids initialization of member

any feedback is appreciated

Well C++ does indeed forbid in-class initialisation of constants, except
for integral constants.

So you have to initialise your constant outside the class, in a source
file, instead. Is there any reason why this is a problem?

john
 
J

John Harrison

Well C++ does indeed forbid in-class initialisation of constants, except
for integral constants.

So you have to initialise your constant outside the class, in a source
file, instead. Is there any reason why this is a problem?

john

I missed that you haven't declared your constant as static, is there any
reason for this?

Normally you would do something like this

// in header file
class MyClass
{
static std::string MY_CONSTANT;
};

// in source file
std::string MyClass::MY_CONSTANT = "permanent value";

john
 

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,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top