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


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 to whatsapp

More Questions from Object Oriented Concepts Module 1

Basic concepts (features) of Object-Oriented Programming C++
View
Friend function in C++ with Programming example
View
What are the basic differences between the POP (Procedure Oriented Programming) and OOP (Object Oriented Programming)?
View
What is an inline function? Write a C++ program to find the maximum of two numbers using inline function.
View
Static member and count the number of objects in C++
View
Function Overloading with an Example in C++
View