When we declare a normal variable (data member) in a class, different copies of those data members create with the associated objects.
In some cases when we need a common data member that should be same for all objects, we cannot do this using normal data members. To fulfill such cases, we need static data members.
Static Variables in C++
Static Data members are created using "static" keyword in C++. The properties of static member variables are similar to that of a C static variable. A static member variable has certain special characteristics. These are:
The out put of the above program is
count:0
count:0
count:0
After reading data
count:3
count:3
count:3
In the above program, the following line was written, to define static data members.
Static Methods in C++
Like static member variables, we can also have static member functions. A member function that is declared static has the following properties:
class-name::function-name;
For example
In some cases when we need a common data member that should be same for all objects, we cannot do this using normal data members. To fulfill such cases, we need static data members.
Static Variables in C++
Static Data members are created using "static" keyword in C++. The properties of static member variables are similar to that of a C static variable. A static member variable has certain special characteristics. These are:
- It is initialized to zero when the first object of its class is created. No other initialization is permitted.
- Only one copy if the that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created.
- It is visible only within the class, but its lifetime is the entire program.
The out put of the above program is
count:0
count:0
count:0
After reading data
count:3
count:3
count:3
In the above program, the following line was written, to define static data members.
int item::count;This is necessary because the static data members are stored separately rather than as a part of an object.
Static Methods in C++
Like static member variables, we can also have static member functions. A member function that is declared static has the following properties:
- A static function can have access to only other static members (functions or variables) declared in the same class.
- A static member function can be called using the class name as follows
class-name::function-name;
For example
using namespace std; class Demo { private: static int X; public: static void fun() { cout <<"Value of X: " << X << endl; } }; //defining int Demo :: X =10; int main() { Demo X; X.fun(); return 0; }
0 comments :
Post a Comment
Note: only a member of this blog may post a comment.