♠ Posted by Unknown in CPP Language at 07:17
Static Class Members
A
data members of a class can be qualified as static. A static member variable
has certain special characteristics. These are :
1.
It is initialized to zero when the first
object of its class is created. No other initialization is permitted.
2.
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 created.
3.
It is visible only within the class, but its
lifetime is the entire program.
Static
variables are normally used to maintain values common to the entire class. for
example a static data member can be used as a counter that records the
occurrences of all the objects.
Like
static member variable, we can also have static member functions. A member
function that is declared static has the following properties:
1.
A static function can have access to only
other static members (function or variables) declared in the same class.
2.
A static member function can be called using
the class name (instead of its objects) as follows:
Class_name
:: function_name;
For Example:
#include<iostream.h>
#include<conio.h>
class
StaticExa
{
static int count;
public:
StaticExa()
{
count++;
cout<<count<<
" Object is Created...."<<endl;
}
static void display()
{
cout<<"Total
"<<count<<" Objects are Created...."<<endl;
}
~StaticExa()
{
cout<<count<<"
Object is Destroyed...."<<endl;
count--;
}
};
int
StaticExa :: count;
void
main()
{
clrscr();
StaticExa st[10];
StaticExa :: display();
getch();
}
0 comments:
Post a Comment