Class variable
In object-oriented programming with classes, a class variable is a variable defined in a class (i.e. a member variable) of which a single copy exists, regardless of how many objects of the class exist.
A class variable is the opposite of instance variable. It is a special type of class member.
In C++ and C#, class variables are declared with the storage class keyword static
, and may therefore be referred to as static member variables.
The same dichotomy between instance and class members applies to methods ("member functions") as well; a class may have both instance methods and class methods. Again, C++ and C# use the keyword static
to indicate that a method is a class method ("static member function").
Example
struct Request {
static int count;
int my_number;
Request() {
my_number = count; // modifies the instance variable "this->my_number"
++count; // modifies the class variable "Request::count"
}
};
int Request::count = 0;
In this example, the class variable Request::count
is incremented on each call to the constructor, so that Request::count
always holds the number of Requests that have been constructed, and each new Request object is given a my_number
in sequential order. Since count
is a class variable (also known as a static member variable), there is only one object Request::count
; in contrast, each Request object contains its own distinct my_number
field.