11.13 — Static member variables

Review of static keyword uses

In the lesson on file scope and the static keyword, you learned that static variables keep their values and are not destroyed even after they go out of scope. For example:

This program prints:


Note that s_id has kept its value across multiple function calls.

The static keyword has another meaning when applied to global variables -- it gives them internal linkage (which restricts them from being seen/used outside of the file they are defined in). Because global variables are typically avoided, the static keyword is not often used in this capacity.

Static member variables

C++ introduces two more uses for the static keyword when applied to classes: static member variables, and static member functions. Fortunately, these uses are fairly straightforward. We’ll talk about static member variables in this lesson, and static member functions in the next.

Before we go into the static keyword as applied to member variables, first consider the following class:

When we instantiate a class object, each object gets its own copy of all normal member variables. In this case, because we have declared two Something class objects, we end up with two copies of m_value: first.m_value, and second.m_value. first.m_value is distinct from second.m_value. Consequently, the program above prints:


Member variables of a class can be made static by using the static keyword. Unlike normal member variables, static member variables are shared by all objects of the class. Consider the following program, similar to the above:

This program produces the following output:


Because s_value is a static member variable, s_value is shared between all objects of the class. Consequently, first.s_value is the same variable as second.s_value. The above program shows that the value we set using first can be accessed using second!

Static members are not associated with class objects

Although you can access static members through objects of the class (as shown with first.s_value and second.s_value in the example above), it turns out that static members exist even if no objects of the class have been instantiated! Much like global variables, they are created when the program starts, and destroyed when the program ends.

Consequently, it is better to think of static members as belonging to the class itself, not to the objects of the class. Because s_value exists independently of any class objects, it can be accessed directly using the class name and the scope resolution operator (in this case, Something::s_value):

In the above snippet, s_value is referenced by class name rather than through an object. Note that we have not even instantiated an object of type Something, but we are still able to access and use Something::s_value. This is the preferred method for accessing static members.

Defining and initializing static member variables

When we declare a static member variable inside a class, we’re telling the compiler about the existence of a static member variable, but not actually defining it (much like a forward declaration). Because static member variables are not part of the individual class objects (they are treated similarly to global variables, and get initialized when the program starts), you must explicitly define the static member outside of the class, in the global scope.

In the example above, we do so via this line:

This line serves two purposes: it instantiates the static member variable (just like a global variable), and optionally initializes it. In this case, we’re providing the initialization value 1. If no initializer is provided, C++ initializes the value to 0.

Note that this static member definition is not subject to access controls: you can define and initialize the value even if it’s declared as private (or protected) in the class.

If the class is defined in a .h file, the static member definition is usually placed in the associated code file for the class (e.g. Something.cpp). If the class is defined in a .cpp file, the static member definition is usually placed directly underneath the class. Do not put the static member definition in a header file (much like a global variable, if that header file gets included more than once, you’ll end up with multiple definitions, which will cause a compile error).

Inline initialization of static member variables

There are a few shortcuts to the above. First, when the static member is a const integral type (which includes char and bool) or a const enum, the static member can be initialized inside the class definition:

In the above example, because the static member variable is a const int, no explicit definition line is needed.

Second, static constexpr members can be initialized inside the class definition:

An example of static member variables

Why use static variables inside classes? One great example is to assign a unique ID to every instance of the class. Here’s an example of that:

This program prints:


Because s_idGenerator is shared by all Something objects, when a new Something object is created, the constructor grabs the current value out of s_idGenerator and then increments the value for the next object. This guarantees that each instantiated Something object receives a unique id (incremented in the order of creation). This can really help when debugging multiple items in an array, as it provides a way to tell multiple objects of the same class type apart!

Static member variables can also be useful when the class needs to utilize an internal lookup table (e.g. an array used to store a set of pre-calculated values). By making the lookup table static, only one copy exists for all objects, rather than making a copy for each object instantiated. This can save substantial amounts of memory.

11.14 -- Static member functions
11.12 -- Const class objects and member functions

166 comments to 11.13 — Static member variables

  • yeokaiwei

    Dear Nascar,
    Microsoft Visual Studio 2019 has just released an update called Version 16.8.3 in December 2020. The compiler configuration options for C++ language standards have changed. It is now separated into C++ and C standards.

  • Karl Phazer

    So, a static class member variable can be initialized inside class definition if it is declared as inline:

    But what happens to the variable during compilation? Inline function calls are replaced with code inside the function body, but what happens to the static inline variable? Is it placed somewhere in the code outside the class definition and if so, where?

    • Karl Phazer

      I'm truly sorry for posting my questions here so light heartedly. After posting the one above, I tried searching for the answer from Stack Exhcange in order to delete it if I found one and I kind of did, but it took me more than hour so unfortunately I can't delete it anymore. I shouldn't have posted the question in the first place before googling for the answer. But now that I might be little bit wiser, let's see if I got it right.

      Obviously the assumption that inline would work in this context similarly as with normal functions is absurd. So, maybe inline here does something similar as with constant variables. It would make sense to me that inline would allow member variables exemption from the one definition rule so that it would be ok even if the class would be defined in multiple places (via #includes)- there should still only exist the one and same identical implementation of it everywhere. I tried to initialize an already-inside-class-initialized static inline class member variable outside the class definition and was happy to find it out it did not compile. It would not have made any sense to be able to do that.

      So it maybe I pretty much got it? What I still can't understand is, why couldn't static class member variables (without inline) just act like static variables inside functions - the declaration/definition statement is only executed once and then given static duration.

      I've had my first steps with OOP by learning Java and at the time it took me a while to understand the whole concept of static members belonging to the class and not the objects but when I did, it seemed very practical and smart. Java was also much simpler compared to C++ and I have to fight the urge to hang on to the principles I got used to with it. Just trying to explain my angst towards the need for inline prefix.

      • nascardriver

        "inline" has 2 meanings.
        (a) Copy a function's instructions to the caller
        (b) C++ `inline` that allows multiple definitions of something

        Forget everything about (a). That's solely a compiler optimization and almost unrelated to (b). I know the lesson on learncpp says otherwise. It needs to be updated.

        The problem with non-inline static class member variables is that their definition (If they were defined inside the class) appears multiple times. It appears in every file that defines the class, ie. every file that includes the header in which the class is defined. This breaks the one-definition-rule. To solve this issue, the variable needs to be either defined in a source file (Which only gets compiled once), or the variable needs to be `inline`, so it can be defined multiple times as long as all definitions are the same.

        • Karl Phazer

          "Forget everything about (a). That's solely a compiler optimization and almost unrelated to (b). I know the lesson on learncpp says otherwise. It needs to be updated."

          Yeah, I think it is already mentioned in the lesson here that inline functions are pretty useless since compiler optimizations do this anyway if they see fit. Still, it was good to hear from you it's best just ignore that use of the word.

          "The problem with non-inline static class member variables is that their definition (If they were defined inside the class) appears multiple times. It appears in every file that defines the class, ie. every file that includes the header in which the class is defined. This breaks the one-definition-rule. To solve this issue, the variable needs to be either defined in a source file (Which only gets compiled once), or the variable needs to be `inline`, so it can be defined multiple times as long as all definitions are the same."

          Yes, I finally got it.. But still, I just can't see a situation where it would cause any problems if static member variables would behave as static variables inside functions - after the first time, the initialization is simply ignored. Sort of implicit #pragma one style applied here would be my preference.

          On the other hand, function and class member variables aren't exactly comparable and since inline in C++ is used 'to set free from the ODR' it is consistent to insist its use in the case of member variables. Also, maybe there's backwards compatibility issues here that I'm unable to understand.

          I'll just surrender now to the fact that I have to use it in order to initialize static variables inside class since it doesn't really seem to have any ill repercussions. Main thing is there's a way to not have to initialize them outside the class definition. That's just perverse :)

          Enough thinking aloud in the comment section already.

          Thank you for the patience to explain these things.

          • nascardriver

            > if static member variables would behave as static variables inside functions
            Those aren't comparable. Functions are executed at some point, class definitions aren't. Static variables in functions can be initialized the first time execution passes through them, but execution never passes through a class definition.

            • Karl Phazer

              That's a very illuminating point!

              • Karl Phazer

                This is not as obvious to a beginner it maybe should be, at first saying 'execution never passes through a class definition' sounds a bit absurd. Why even write it then? Well, the code and data inside the class will be used of course, but the body of the class will never be executed line by line as code inside a function body. This is especially true for static members, since objects (actual instances made out from from the class 'blueprint') are initialized instantiatioan (?) and I'd think that would mean also initializing the normal (non-static) (aka instance members, at least in Java) members. For pure static classes, there is no clear point in compile or run time when this would happen.

                Now that I used the terms myself, there was a passage somewhere in the lessons (can't unfortunately remember exactly where right now) that said something like 'instantiated but not initialized' which made me scratch my head for a while. My current  interpretation is that instantation refers to allocating memory for the object and initialization would be assigning actual values to its members.

                I'm sure I got something wrong there so if you could correct those for me, this might end up being one our most fruitful dialogues.


                • nascardriver

                  > instantiated but not initialized
                  I'm curious where you read that. When a class is instantiated (A variable of this class' type is created), it gets initialized. "Initialization" however doesn't necessarily mean that all members get a value and are safe to use.
                  If the class explicitly initializes some members, but not others, those "others" are default-initialized. For fundamental types, default-initialized means they are initialized to an indeterminate value and reading from them causes undefined behavior. That's what we call uninitialized (Although technically, they are initialized).

                  • Karl Phazer

                    I tried searching for the phrase I was referring to but couldn't find anything so my memory was probably just playing tricks on me (maybe I read it somewhere else). I think instantiation is a bit vague term at least if compared to initialization.

                    I personally associate instantiation primarily with the process of creating (class based) objects (as opposed to fundamental types) but I guess instantiation and initialization can be used interchangeably.

                    tl;dr - never mind    :)

  • MrGeeBee

    What's the difference between these?

    Both seems to work fine, since showCount() doesn't change any value, is it better to have const or should it be static since I call a static member?

    • nascardriver

      If `showCount` doesn't access any non-static members and its foreseeable that it won't need access to any non-static members in the future, it's better to make `showCount` `static`.

  • Michael

    I am trying to create a couple static const vectors and I have a couple questions:

    Code snippet in question:

    1. Without the 'inline' keyword, I am not able to initialize the vectors to the string values I specified. What is inline doing in this case that allows me to perform the uniform initialization? Would it be better to declare the variables outside the class to save on run-time performance? This case may not be super significant but I want to make sure I am already following the best practices on the small stuff.

    2. When I change 'const' to 'constexpr' it is complaining that "a constexpr variable should have a literal type or a reference type". I tried simplifying it by switching the vector to contain int instead of std::string but I get the same error. How can we use constexpr for std::array and not std::vector?

    • nascardriver

      1. You cannot define `static` member variables inside the class unless they are `inline`. That is because the compiler wouldn't know when to initialize the variable when it appears in multiple source files (Through includes). By making them `inline`, you're allowing the variable to be defined multiple times. Without `inline`, you can declare the variable in the class and define it outside in a source file.

      2. `std::vector` cannot be `constexpr` (Until C++20), because it uses dynamic memory allocation, which requires a run-time. If you know how many elements your list will have (You do know), use `std::array`. `std::array` can be `constexpr` if the element type can be `constexpr`.
      `std::string` cannot be `constexpr` for the same reason as `std::vector`. Use `std::string_view`.

  • salah

    Hi nascardriver and Alex,

    Why we can't initialize and define non_const static variable in the class ?

    • If C++ allowed initialization of non-const static variables this meant that the variable needed to be stored separately in memory for each object created.

      Whereas if the static variable is const the compiler simply inlines such class member i.e, they are not stored in memory of each object anymore.

      Nas and Alex can give a more good explanation.

    • nascardriver

      Const or non-const, doesn't matter, both are stored independent of the objects. The number of instances doesn't matter.
      `static` `const` member variables can be stored in the binary itself, they don't have to be initialized at run-time (You can only initialize `static` `const` members with constant expressions).
      If you take away the `const`, the variable has to be initialized at run-time. But there are multiple definitions of a class (That's ok, classes can be defined multiple times in different files), so when does the variable get initialized and how is it prevented that it gets initialized multiple times? This is solvable by making the variable also `inline`, but that adds a run-time cost (To check if the variable has been initialized already). If, on the other hand, the variable is only declared in the class, but defined in a source file, then there is only one definition of the variable and we don't have to worry about multiple definitions.

  • salah

    why counter remained 2 ?
    I think because I don't have the appropriate Constructor, but I tried adding one and it didn't work

    • nascardriver

      Line 22 and 23 don't invoke the default constructor, they invoke another type of constructor, the copy constructor. We cover it later.

  • limcheling

    Hi, Alex,

    Let's say I have 8 Derived classes which contains multiple 2D arrays(50x180 int) with prefixed data (Arr1, Arr2...Arr7) each. During runtime, there will only be 1 object of class DeriveX (X:1..8) created on heap. Currently, those arrays are all static int Arr1[50][180]. I wonder how to make decision if one should choose their array to be static member variable OR just member variable? My understanding is if all those arrays are static, all of them would be created in Data Segment before any instance is created. So isn't it better to make them non-static so to save memory space?

    The structure is like this:

    class Base
    //some other things common for all Derived

    class Derived1: public Base
       Derived1(int nArrType)
         case 1: //for loop to assign data in Arr1 to ArrMain
         //continue till case 7
       static int ArrMain[50][180];
       static int Arr1[50][180];
       static int Arr2[50][180];
       //....till Arr7

    //Define static arrays here with fixed data

    //Continue with class Derived2 to Derive8 with same structure

    class MyGame
        Base* pGame;

        Init(int nGameType, int nArrType)
          case 1: pGame = new Derived1(nArrType); break;
          //continue to case 8


    On top of this, I would like to replace C-Style array by STL container as not all Arrays need 50x180 items, 180 is just the max needed. so i have the problem choosing container, could you advise?

    Lastly, I feel that once a nArrType is chosen, all ArrX's data is assigned nArrMain seems not a good method. If I use vector of vector, i can just assign nVecMain = nVecX; Could you also advise on this?

    Thanks very much

    • nascardriver

      Don't make decisions about where to store something based on memory usage unless you're developing for a system with restricted memory. Make decisions based on code. You need one array per instance? Don't make it static. You need one array per class? Make it static.

      It's impossible to suggest a container without knowing how you're going to use it. Listen to this talk. If you're unsure after that, ask again.

      • limcheling

        Thanks for the reply and the link, I get the idea to choose the container type but still not clear about static/non-static.

        Though in general, you said static or not, it should depends on code. But the code situation is I will always have 1 and only 1 instance of DeriveX object(X: 1..24). Base* pGame can point to Derived1 or Derived2 or whichever Derived depends on argument during runtime but there will only one object Derived, always. And once created, it lasts till termination.

        And each Derived has multiple arrays Arr1 to Arr7. In fact, much more, it is Arr1 to Arr15. Out of the 15 array, only 1 will be chosen during initialisation and the chosen one is assigned to ArrMain. From then onwards, ArrMain would be assessed but not modified anymore.

        My worries is it seems too much waste/heavy to create so many arrays but in fact, only an array will be chosen and used per each execution.

        Total arrays: 24 classes x 15 arrays/class x array size 50x180 x 4bytes = 13Mb
        Array needed during each run: 1 array of 50x180 x 4bytes.

        Is the concern justified? If so, what should I do?

        Thanks for any help.

        • nascardriver

          Thanks for elaborating your situation. The concern is justified. Allocate the DeriveX dynamically and make the array a non-static member of DeriveX.

  • terapty

    >Second, as of C++11, static constexpr members of any type that supports constexpr initialization can be initialized inside the class definition

    Can you explain this in a bit more detail?
    Does it mean that before C++11, constexpr members could be defined but initialized right away? Or does it just mean that you can't initialize them INSIDE the class?
    I'm also a bit confused about the "any type that supports constexpr initialization" part. Are you saying some types can't be initialized when they're declared constexpr?

    • nascardriver

      That sentence doesn't make sense, `constexpr` didn't exist before C++11. I've removed the C++11 part from the lesson.

      > Are you saying some types can't be initialized when they're declared constexpr?
      Everything that's `constexpr` can be initialized (And has to be initialized). But not all types can be `constexpr`. Types that require a run-time (eg. `std::string` (For dynamic allocation) (As of C++17, might change in C++20)), can't be `constexpr`.

  • Mingrui Zhang

    I think maybe we can add a small section to talk about const static members as a warning to the people:
    Since they cannot be initialized within the class definition.

  • Fan

    In "inline initialization of static member variables", does the inline mean that the "one definition rule" is overriden? Otherwise I guess if the definition of a class with inline initialization of static member variables is included in multiple files it will violate the "one definition rule".

  • Anthony

    Hi again,

    I'm currently browsing a project where they've made a whole bunch of classes where each class has a static pointer named 'singleton' pointed at the class itself, like this:

    Could you tell me why they're doing this?

    • Anthony

      Just to add a little detail, it's more like this:

      Why have a static pointer that would point to every instance of the class, and assign it a value of `this`, which surely applies to a single instance? If you instantiate A, `singleton = this;` causes the linker to error with 'undefined reference'.

    • nascardriver

      That's a singleton class, ie. a class of which only 1 instance can exist. The way the code looks, I'd say they're creating an `A` at some other point, because it depends on some other code to have run first. They only create an `A` one time! After that, whenever they want to use an `A`, they do

      Singletons are like global objects, but more complex.

      > If you instantiate A, `singleton = this;` causes the linker to error with 'undefined reference'.
      The `singleton` in line 3 is only a declaration. The variable needs to be defined outside of the class, as shown in this lesson.

      • Anthony

        I see now. So we write the following definition outside the body of the class (typically in the .cpp):

        Excellent. Thank you.

  • Samira Ferdi

    Hi, Alex and Nascardriver!

    So, correct me if I'm wrong, the meaning of static member variable are:
    1. That member variable is shared between all objects of the class. So, any objects of the class refer the same original member variable of the class (not the copy). It's analogues with many references that refer to the same normal variable. It means all changes from one identifier affect all.

    2. Who can access that static member variable. Static member variable can be accessed through it's class itself because it belongs to the class or through the instantiated class (the object of the class) with the effect that explain in point 1 above. Non-static member variables can only be accessed through the object of the class and cannot be accessed through it's own class.

    3. Static keyword means when apply to a class is, to access the members of the class, we  don't have to instantiated the class, although it's fine if we access the static members through the object of the class (of course with consideration of the exceptional things).

    Alex, if you feel my explanation makes the meaning of static member variable clearer, I hope you can update this lesson for clearer explanation at the first place.

    But, I'm not sure that I understand why static non-const member variable should initialized (or define) outside the class. Is this initialization outside the class is a statement that "these (static) member variables are not belong to the objects of the class" as static member variables belong to the class itself and because all non-static member variables that define inside a class belong to the object of that class? So, the static keyword in this term is like the separation of what belong to who. But, this understanding is not safe (apply in general) because the object of the class can have (access) the static member variables of the class. Any thought?

    • nascardriver

      1. Correct.

      2. Correct. `static` member variables are affected by access specifiers (private, protected, public), which can restrict access from the outside.

      3. Correct.

      > why static non-const member variable should initialized (or define) outside the class
      As most variables, a static member variable must only be defined once. Since the class declaration occurs many times (Everywhere where its header is included), it wouldn't be clear who is responsible for the initialization if the definition was in the header. .cpp files only get compiled once, so we can define and initialize the variable there.

  • Nguyen


    In the last example, I assume that s_idGenerator @ line 8 keeps its value and is not destroyed even after it goes out of scope and therefore when a new Something object is created, the constructor grabs the current value out of s_idGenerator and then increments the value for the next object.  Please let me know if my assumptions are correct.


  • hellmet

    Hello Nascardriver and Alex!
    Hellmet again with doubts!
    1) "Note that this static member definition is not subject to access controls: you can define and initialize the value even if it’s declared as private (or protected) in the class."

    What does that mean? If that means to say that "private is of no use, anyone initialize that variable!", then okays! No issues.

    2) Having been taught Python before C++; I tried to use Something.s_idGenerator, which was clearly incorrect. Any reasoning as to why the namespace resolution operator was used here? (It is the standard, true, but a technical and/or simple explanation would help me understand the language better!)

    3) "Do not put the static member definition in a header file (much like a global variable, if that header file gets included more than once, you’ll end up with multiple definitions, which will cause a compile error)". So, this means that I can safely initialize my static class variable to the value I want and am rest assured that no one can use that same 'definition' to 'override' my definition, right?
    Say a client put his own 'int Something::s_idGenerator = 1;' before his main while using my library (via source header files and precompiled library). The imports happen fine, but the linker fails complaining that there was a redefinition, right?

    Thank you!

    • nascardriver

      Yes, anyone can initialize the variable. Just like anyone can define private member functions.

      A class with static members is more like a namespace than like an instance. I don't know if that's the reasoning, but it seems good to me.

      I never even thought of trying that. But yes, the linker will complain about multiple definitions. Like member functions, static member variables should be initialized in a corresponding source file.

  • Phuc

    Hello !
    Why method (int getID() const { return m_id; }) is const But the object created is not const but it still calls the method const

  • Samira Ferdi

    Hi, Alex and Nascardriver!

    What do you mean 'copy'? I often very confuse about this term.

    • When multiple objects have the same value and will always have the same value, they're copies of each other.

  • mmp52

    Why do we use "int" declaration here? Don't we already have the definition of the static member variable when we define the class itself?

    I was expecting a direct assignment:

    • Alex

      No -- what's in the class (static int s_value) is a declaration.

      In order to be instantiated, the variable needs a definition. The top one is a definition. The bottom one is just a statement.

  • McDidda

    why definitions of static member function/variable (defined outside of class) doesn't have "static" keyword  used to define the function/variable?

    • Alex

      I'm actually not sure. Anybody else have any insights on why the definition/initializer doesn't require the static keyword?

      • The function definition cannot be ambiguous, ie. it can be uniquely resolved to its declaration, even without `static` at the definition. Just like `virtual` or default arguments, adding `static` to the definition would be redundant.

  • McDidda

    Could you please explain the reason for not defining/initializing static member s_value inside class Something, and instead defining it outside, but in case of const static member variable we define it inside class?

    • Alex

      If the static is a const integral value, the compiler can usually optimize it away. Otherwise, it needs to be defined outside the class because it's essentially a global variable, not tied to objects of the class.

      • Michael Djamoos

        Also, since the variable is essentially a global variable, you would not want each new object instantiation to initialize it again.

        • Alex

          While true, C++ handles this fine for local static variables, which can have an initializer, but are only initialized once despite the initializer being inside the function.

  • sekhar

    Hi Alex, Tutorials are amazing and leaned a lot, Thanks for these awesome tutorials.

    Have a question for below code snippet :

    Just need clarity if really makes sense to apply const to static member functions/objects in a class and why const can't be applied to static function even though it gets invoked with static const object ?

    • * Line 13, 3, 8: Initialize your variables with brace initializers.
      * Line 15, 26: Limit your lines to 80 characters in length for better readability on small displays.
      * Don't use "using namespace".

      static members aren't linked to an object. s.getstatic() is the same as Sample::getstatic().

      • sekhar

        Thanks nascardriver. Could you please let me know the reason why const can't be applied to static member functions ? Is there any particular reason that you can think of ?

        • There's no reason why this should be possible. They aren't members of an object, so the pseudo-object they're accessing can't be const, so they can always modify it and you can always call them.
          Marking those functions const would only help you to not accidentally modify any static members in a function where you didn't intend to. Just like marking pass-by-value arguments as const, this has no practical effect.

          • Fan

            Maybe another reason is that the "const" in member functions really means that the this pointer passed to the function is pointing a const object. Static member functions do not operate on objects, so they do not have a this pointer as an argement, so there is no way to make the this pointer constant.

  • Matty J

    So let's say you build a class Monster, and nest a class Keese within it.
    Let's say you wanted Link's level (Zelda is now an RPG in this example) to scale the Keese's health
    You could write Monster::Keese::m_health += 1.2 * levelLink to scale all Keese (normal, fire, etc.) instead of each one individually

    This example is probably better with Oblivion, but I've already typed it

  • prabhu

    Hi Alex/Nascardriver,

    I have a question on inline initialization on static member variable.
    When we initialize like
    static int a; , we have to define the variable outside the class , and duration/scope of the variable will be persist till end of class and the static variable belong to class rather then object, so it will get updated every time its called through object or scope resolution operator. I am ok with the above points.

    if i define & declaration  like const int a =10 ;
    here I should initialize the content in the declaration itself since its const and it will not allow us to update the value of a .I am ok with the above points here also

    But If i declare and define like static const int a = 10 means ,
    what are the properties , it will take forward from static and const.

  • Udit

    The lookup table example could be:

  • Micah

    Why does it print backwards if you don't initialize a new std::cout call?
    output for this is:
    3 2

    • Hi Micah!

      The evaluation order of multiple << is undefined.

      • Micah

        Thanks, I see, then different statements guarantee evaluation order.
        Okay then a couple questions if you don't mind..
        If they are undefined in evaluation order, why do they evaluate backwards? Does the computer just have to assume how to print and evaluate with the operator? And if so, why does it assume the same way each time?
        Would that not be an update-able fix to reverse the process?
        And, is there another way to send multiple calls like this to the console on one line? Or is this just a qwerk of C++?

        • The compiler decides the evaluation order. Yours appears to evaluate the statement backwards. As long as you're using the same compiler, you'll get the same results.

          > Would that not be an update-able fix to reverse the process?
          Reversing the order is probably easy, but the c++ standard doesn't state a specific order, so there is no reason to choose one way over the other.

          > is there another way to send multiple calls like this to the console on one line?
          Store the values in temporaries before printing them

          The behavior of this code is the same across all compilers.

  • Aditi

    Thank you for the great examples . They were really easy to understand and explained the concept very well :)

  • Dr. Khalid Alharbi

    Hi Alex,

    I think static member definition and initialization is not subject to access controls,but static members that are under private section cannot be accessed directly using the class name or through objects of the class. We need to use static member functions to access (i.e., read and/or write) static data members.
    The following code works fine, but if you try to run the comments you will receive an error: ‘int Something::s_value’ is private within this context.

    #include <iostream>
    using namespace std;
    class Something
         static int getvalue()
             return s_value;
         static void setvalue()
          static int s_value;

    int Something::s_value=0 ;

    int main()
        Something first;
        Something second;

        //first.s_value = 2;
       // cout << first.s_value << '\n';
       //cout << second.s_value << '\n';
       //cout << Something::s_value << '\n';
       cout << Something::getvalue() << '\n';
        return 0;

  • Peter Baum

    The static member definition and initialization looks just like a global to me in terms of where it is defined and its function.  The only thing slightly different is that it is namespace qualified by the class name.  Is there anything else that differentiates it from an ordinary global?

  • April

    How is it that the first, second, and third objects can access the getId member function if it is const and the objects themselves are not?

    • nascardriver

      Hi April!

      Non-const objects can access const-functions (The object is allowed to be modified, the function doesn't modify anything, everything is fine).
      Const objects can't access non-const functions (The object is not allowed to be modified, the function wants to modify the object, not allowed).

  • Arnav Borborah

    You have written:

    "Second, as of C++11, static constexpr members of any type can be initialized inside the class definition:"

    Does this apply for classes without constexpr constructors? How would they be initialized at compile time? (I presume they won't since classes such as std::vector use runtime dynamic allocation)

    • nascardriver

      Hi Arnav!

      I'm not sure if I got your question right since what you wrote isn't related to your quote.

      The quote states that this is allowed

      What (I think) you asked is having a constexpr object of a type without a constexpr constructor

    • Alex

      constexpr variables aren't initialized at compile time (they are initialized at run-time). However, the value they are initialized with must be known at compile time.

      C++ doesn't currently support const (or constexpr) constructors in any case.

      • Arnav Borborah

        Alex, C++ actually [does support `constexpr` constructors]( (Scroll down a bit to see it).

        nascardriver, I'm asking that if I am allowed to do:

        When CNonConst does NOT have a constexpr constructor. I am confused about why it says "any type" when this is not allowed for classes without a constexpr constructor.

        • Alex

          1) I stand corrected!
          2) I see what you're getting at. I'll amend the text to be more specific that this applies only to types that can actually be created as constexpr.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]