Program:
// To illustrate Static Class data and static Function
// Program coutns the number of instances or objects created
#include <iostream>
using namespace std;
class statgeek
{
int id;
static int count;
// declaring a static variable
public:
statgeek()
{
count++; // incremented each time a objet is created
id=count;
}
void print()
{
cout<<"ID is :" <<id<<endl; } //to print the id of
the object
static void
printcount()
{ cout<<endl<<"The number
of objects created are:"<< count<<endl;} // a static function
};
int
statgeek::count=0;
int main()
{
statgeek obj1;
//count will be incremented
cout<<"Object1 :"; obj1.print();
statgeek obj2;
//count will be incremented
cout<<"Object2 :"; obj2.print();
statgeek obj3;
//count will be incremented
cout<<"Object3 :"; obj3.print();
statgeek::printcount(); // static function can be called without
associating with the object
}
}
Output:
Comments
Post a Comment