Why static const string = "NA"; is not allowed inside the class.

T

Thinking_In_CPP

Hi All,

I have a query

Why static const string = "NA"; is not allowed inside the class when
the standard allows

static const int = 5; inside the class

Please Explain.
 
M

Martin York

Hi All,

I have a query

Why static const string = "NA"; is not allowed inside the class when
the standard allows

static const int = 5; inside the class

Please Explain.


Because converting "NA" which is "const char * const" (or something
similar) in-to a std::string requires you to call the constructor.

While 'static const int' members can be optimized completely out of
the code and not even require storage space (if you are lucky). This
special case was recognized as a an easy optimization and added to the
language for this reason.
 
J

Jeff Schwab

Thinking_In_CPP said:
Hi All,

I have a query

Why static const string = "NA"; is not allowed inside the class when
the standard allows

static const int = 5; inside the class

Please Explain.

http://www.research.att.com/~bs/bs_faq2.html#in-class

"So why do these inconvenient restrictions exist? A class is typically
declared in a header file and a header file is typically included into
many translation units. However, to avoid complicated linker rules, C++
requires that every object has a unique definition. That rule would be
broken if C++ allowed in-class definition of entities that needed to be
stored in memory as objects. See D&E for an explanation of C++'s design
tradeoffs."
 
J

James Kanze

I have a query
Why static const string = "NA"; is not allowed inside the class when
the standard allows
static const int = 5; inside the class

Within the class, the declaration of a static member is not a
definition, but a declaration, and declarations can't have
initializers. There's a special exception (aka hack) for
integral types (and only integral types) because constant
integral expressions place a special role in the language, and
in order for an integral constant to be treated as a constant
integral expression, its initializer must be seen.

In sum, it's allowing the initialization for integral types
which is the anomalous exception, not forbidding it for other
types.
 

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,054
Latest member
TrimKetoBoost

Latest Threads

Top