Static Data
2 minute read
Explain static data member with the characteristic of it.
· A class data member can be qualified as static.
· Static variables are normally used to maintain common values throughout the class.
· For example: a static data member can be used as a counter that maintain the records the occurrences of all the objects.
· The type and scope of each static member variable must be defined outside the class definition, because it is stored separately rather than as a part of an object.
· Since they are associated with the class not an object, they are known as class variables.
Example:
class abc
{
static int count;
};
int abc :: count;
- The static variable is initialized to zero when the objects are created.
- Only one (common) copy of static data member is created and it is shared by all objects of the class.
- Static variables are like non-inline member functions as they are declared in a class declaration and defined out side the class.
- Characteristic of static data member are as follow:
- It is initialized with zero when the first object of its class is created. No other initialization is permitted.
- Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are crated.
- It is visible only within the class, but its life is in the entire program.
Explain the static member functions with the characteristics of it.
Syntax:
static return-type function-name(argument list)
{
//Function body
}
- A static member function is directly by the class name, there is no need of an object to call the static member function.
- To call a static member function scope resolution operator (::) is used, like
- class-name :: static-function-name();
Characteristic of static member functions are as follow:
- A static function can access static data (functions or variables) declared in the same class.
- We can call the static member function using the class name (instead of its objects) as follows:
- Class-name :: function-name;