Minti wrote:
How do we initialize static const data in C++, I tried
class Foo
{
static const std::string name = "MyName";
};
I don't see any reason as to why this must not work.
Probably it is because that we are in a sense calling a non static
function[ The constructor of std::string]. But any other soluction(?)
to me would sound inelegant.
But I see no rationale for not allowing
class Foo
{
static const float bar = 23;
};
Can anybody put any _common_sense in this non-sense.
What you are missing is that the above is a declaration, not a definition.
That is:
if you put a static member in a class, you only have declared it!
You still need a definition of that member somewhere and of course,
like anywhere else, you put the initialization to the definition.
Declaration: telling the compiler that somewhere, in a code snippet far far
away, something exists and what it looks like
Definition: reserves the actual memory for that something
So back to your example:
class Foo
{
static const std::string name; // Declaration
};
const std::string Foo::name = "MyName"; // Definition
Remember
There is the famous One-Definition-Rule. Which means:
you can have as many declarations in a program as you want (as long
as all of them coincide). But you can have only 1 defintion. Thus
typically the following is done. The declaration (enclosed in the class
declaration) goes into the header file, while the defintion (with the
initialization) goes into the source code file, which implements the
class functionality.
--
Karl Heinz Buchegger
kb******@gascad.at