Search code examples
c++statefunctor

What does "state" mean in C++?


When I was looking for explanations of C++ functor, I saw the following statement, "There are a couple of nice things about functors. One is that unlike regular functions, they can contain state."

Could anybody explain to me what "state" means in C++? Thank you very much.


Solution

  • What does “state” mean ...

    The word has multiple meanings and contextual subtleties.

    Here is a general definition for the word from a dictionary:

    a condition or way of being that exists at a particular time


    ... in C++?

    There is no C++ specific meaning for the word as far as I know. It is not something specified by the language. The meaning is same as in programming or computer science in general.

    Here is a computer science specific definition:

    In information technology and computer science, a system is described as stateful if it is designed to remember preceding events or user interactions; the remembered information is called the state of the system.

    The state of a C++ program consists primarily of the representation of objects.


    "There are a couple of nice things about functors. One is that unlike regular functions, they can contain state."

    While this is "true enough" in practice, it is a simplification. Technically regular functions can "contain" global state. But that is probably ignored by the author of that quote since global state is problematic and something that should be avoided.