Raj Kumar
Computer Science And Engineering

Static member and count the number of objects in C++

Object Oriented Concepts

Explanation

1158    0
A static member is shared by all objects of the class. Static data members hold global data that is common to all objects of the class. Examples of such global data are count of objects currently present, common data accessed by all objects, etc.
A static data member has certain special characteristics:
It is initialized to zero when first object is created. No other initialization is permitted. Only one copy of the data member is created for the entire class and is shared by all the objects of class, no matter how many objects are created. Static variables are normally used to maintain values common to entire class objects.
The following program demonstrates the C++ program to count the number of objects created.

 #include<iostream>
 using namespace std;
 class counter
 {
     private:
         static int count;
     public:
         counter()
         {
             count++;
         }
     void display()
     {
         cout<<"The number of objects created are: "<<count;
     }
 };
 int counter::count=0;
 int main()
 {
     counter c1;
     counter c2;
     counter c3;
     c2.display();
 }

OUTPUT:
The number of objects created are: 2

Share:   
   Raj Kumar
Computer Science And Engineering

More Questions from Object Oriented Concepts Module 1