Jump to content

Class variable

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by VolkovBot (talk | contribs) at 13:31, 25 February 2010 (robot Adding: ja:クラス変数). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In object-oriented programming with classes, a class variable is a variable defined in a class 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.