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

 

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

In this tutorial, we will Learn:

What are static members in C++ with Programming example?

Write a C++ program to count the number of objects created.

Solution:

Video Tutorial:

A data member prefixed with a static keyword becomes the static member of a class. Irrespective of the number of objects of the class are created, there exists only one copy of the static member.

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

Summary:

In this article, we understood the concept of Static member and Wrote a C++ program to count the number of objects created.

If you like the tutorial share it with your friends. Like the Facebook page for regular updates and YouTube channel for video tutorials.

Leave a Comment

Your email address will not be published. Required fields are marked *

Welcome to VTUPulse.com


Computer Graphics and Image Processing Mini Projects -> Click Here

Download Final Year Project -> Click Here

This will close in 12 seconds