# Class variable

> Mediated Wiki article. Canonical URL: https://mediated.wiki/source/Class_variable
> Markdown URL: https://mediated.wiki/source/Class_variable.md
> Source: https://en.wikipedia.org/wiki/Class_variable
> Source revision: 1351585973
> License: Creative Commons Attribution-ShareAlike 4.0 International (https://creativecommons.org/licenses/by-sa/4.0/)

Variable defined in a class whose objects all possess the same copy

- [Computer programming portal](https://en.wikipedia.org/wiki/Portal:Computer_programming)

In [class-based](/source/Class-based), [object-oriented programming](/source/Object-oriented_programming), a **class variable** is a [variable](/source/Variable_(programming)) defined in a [class](/source/Class_(programming)) of which a single copy exists, regardless of how many [instances](/source/Instance_(computer_science)) of the class exist.[1][2][3][4][5]

A class variable is not an [instance variable](/source/Instance_variable). It is a special type of [class attribute](/source/Class_(computer_science)#Structure) (or class property, [field](/source/Field_(computer_science)), or data member). The same dichotomy between *instance* and *class* members applies to [methods](/source/Method_(computer_science)) ("member functions") as well; a class may have both [instance methods](/source/Instance_method) and [class methods](/source/Class_method).

## Static member variables and static member functions

See also: [Static method](/source/Static_method)

In some languages, class variables and class methods are either statically resolved, not via [dynamic dispatch](/source/Dynamic_dispatch), or their memory [statically allocated](/source/Static_memory_allocation) at compile time (once for the entire class, as [static variables](/source/Static_variable)), not dynamically allocated at run time (at every instantiation of an object). In other cases, however, either or both of these are dynamic. For example, if classes can be dynamically defined (at run time), class variables of these classes are allocated dynamically when the class is defined, and in some languages class methods are also dispatched dynamically.

Thus in some languages, **static member variable** or **static member function** are used synonymously with or in place of "class variable" or "class function", but these are not synonymous across languages. These terms are commonly used in [Java](/source/Java_(programming_language)), [C#](/source/C_Sharp_(programming_language)),[5] and [C++](/source/C%2B%2B), where class variables and class methods are declared with the [static keyword](/source/Static_(keyword)), and referred to as **static member variables** or **static member functions**.

## Examples

### C++

class Order {
private:
    inline static int nextId = 0;
    int id;
public:
    Order():
        id{nextId++} {}
};

In this C++ example, the class variable Order::nextId is [incremented](/source/Increment_operator) on each call to the [constructor](/source/Constructor_(computer_science)), so that Order::nextId always holds the number of Orders that have been constructed, and each new Order object is given a number in sequential order. Since nextId is a class variable, there is only one object Order::nextId; in contrast, each Order object contains its own distinct id field.

Also note that the variable Order::nextId is initialized only once (as inline static, it is initialized inside the class; prior to [C++17](/source/C%2B%2B17), it was only static and had to be initialized outside the class).

A class with static members that are instances of itself can only declare the fields const first while the [constexpr](/source/Constexpr) declarations must reside outside the class. Trying to use declare a constexpr instance of a class as a static member of itself fails as no definition of an object may be an incomplete type, which the class is incomplete until it is closed.[6]

struct Color {
    uint8_t r;
    uint8_t g;
    uint8_t b;

    constexpr Color(uint8_t r, uint8_t g, uint8_t b) noexcept:
        r{r}, g{g}, b{b} {}

    constexpr ~Color() = default;

    static const Color BLACK;
    static const Color RED;
    static const Color GREEN;
    static const Color YELLOW;
    static const Color BLUE;
    static const Color MAGENTA;
    static const Color CYAN;
    static const Color WHITE;
};

inline constexpr Color Color::BLACK = Color(0, 0, 0);
inline constexpr Color Color::RED = Color(255, 0, 0);
inline constexpr Color Color::GREEN = Color(0, 255, 0);
inline constexpr Color Color::YELLOW = Color(255, 255, 0);
inline constexpr Color Color::BLUE = Color(0, 0, 255);
inline constexpr Color Color::MAGENTA = Color(255, 0, 255);
inline constexpr Color Color::CYAN = Color(0, 255, 255);
inline constexpr Color Color::WHITE = Color(255, 255, 255);

### Python

class Dog:
    vertebrate_group: str = "mammals" # class variable

dog: Dog = Dog()
print(dog.vertebrate_group) # accessing the class variable

In the above Python code, it does not provide much information as there is only class variable in the Dog class that provide the vertebrate group of dog as mammals. In instance variable, one can customize the object (in this case, dog) by having one or more [instance variables](/source/Instance_variable) in the Dog class.

This can also be type hinted using ClassVar.

from typing import ClassVar

class Dog:
    vertebrate_group: ClassVar[str] = "mammals"

## Notes

1. **[^](#cite_ref-TheJavaTurotialVariables_1-0)** ["The Java Tutorial, Variables"](http://download.oracle.com/javase/tutorial/java/nutsandbolts/variables.html). Retrieved 2010-10-21.

1. **[^](#cite_ref-TheJavaTutorialUnderstandingInstanceAndClassMembers_2-0)** ["The Java Tutorial, Understanding Instance and Class Members"](http://download.oracle.com/javase/tutorial/java/javaOO/classvars.html). Retrieved 2010-10-21.

1. **[^](#cite_ref-ThePythonLanguageReferenceCompoundStatements_3-0)** ["The Python Language Reference, Compound Statements"](https://docs.python.org/reference/compound_stmts.html#class-definitions). Retrieved 2010-10-21.

1. **[^](#cite_ref-ObjectiveCRuntimeReference_4-0)** ["Objective-C Runtime Reference"](https://developer.apple.com/documentation/objectivec/objective_c_runtime). *Apple Developer*. Retrieved 1 April 2018.

1. ^ [***a***](#cite_ref-ClassVariablesinCSharp_5-0) [***b***](#cite_ref-ClassVariablesinCSharp_5-1) ["Class Variables in C#"](https://syntaxdb.com/ref/csharp/class-var). *Syntaxdb*. Retrieved 1 April 2018.

1. **[^](#cite_ref-6)** WG21 (23 April 2026). ["Draft C++ Standard - Declarations and definitions"](https://eel.is/c++draft/basic#def-5). *eel.is*. WG21. In the definition of an object, the type of that object shall not be an incomplete type ([basic.types.general]), an abstract class type ([class.abstract]), or a (possibly multidimensional) array thereof.{{[cite web](https://en.wikipedia.org/wiki/Template:Cite_web)}}: CS1 maint: numeric names: authors list ([link](https://en.wikipedia.org/wiki/Category:CS1_maint:_numeric_names:_authors_list))

---
Adapted from the Wikipedia article [Class variable](https://en.wikipedia.org/wiki/Class_variable) by Wikipedia contributors ([contributor history](https://en.wikipedia.org/wiki/Class_variable?action=history)). Available under [Creative Commons Attribution-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-sa/4.0/). Changes may have been made.
