If you want to make money online : Register now

[Solved]: If someone was designing a computer language, why would they require static members to be defined outside the class?

, , No Comments
Problem Detail: 

I am new to C++ and just learned that "The declaration of a static data member in the member list of a class is not a definition. You must define the static member outside of the class declaration, in namespace scope."

I am curious about why this is. Are there particular design advantages to making the rules of the language in this way? I am not asking: "tell me what Stroustrup was thinking when he made C++" -- which I know is an unfair question on these forums. I am asking: if someone sat down to make a computer language, why might they require that static data members are defined outside of the class. What are the advantages of this? What are the disadvantages? What kinds of costs would this incur? Why would someone put this quirk in their language? (Also I'm curious, but I know it's not totally appropriate to ask here: how did this quirk end up in C++).

Asked By : bernie2436

Answered By : Pavel Zaichenkov

Such language design solution makes sense, because class body is basically a declaration, which normally has to be in the header file. All definitions has to appear in cpp files, where class instances are actually used. If you allow static members to be defined inside class body, then you mix declarations with definitions. So I would require this to make separation between declarations and definitions clear.

In terms of this separation it is fine to initialise static const class members inside class body. Basically, you are defining some constant and it could be equivalently done with some #define directive.

It doesn't seem that this restriction is due to the limits of the language or a compiler. Java doesn't have this restriction and allows definitions inside the body of a class for any static data member (not const only).

Update: C++11 relaxes the restriction and supports non-static member in-class initialisation. Static members still have to be defined outside.

Best Answer from StackOverflow

Question Source : http://cs.stackexchange.com/questions/14308

3.2K people like this

 Download Related Notes/Documents

0 comments:

Post a Comment

Let us know your responses and feedback