Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count the number of objects using Static member function in C++ Program
The goal here is to count the number of objects of a class that are being created using a static member function.
A static data member is shared by all objects of the class commonly. If no value is given, a static data member is always initialized with 0. A static member function can only use static data members of that class.
We are using a class Student here. We will declare a static data member count which will store the count of objects. A static member function rollCall(void) will display the count of objects as roll no.s of students in a class.
Approach used in the below program is as follows
-
We declare a class Student which has public data members int rollno and static data member count.
-
There is a constructor that calls rollcall() and initializes rollno with the count.
-
There is a destructor that decreases count.
-
Static member function rollcall() displays the count of objects as Student count and increments the count.
-
Each time the object of Student is created, the constructor calls rollcall() and count is incremented. This count is assigned to rollno of that Student object.
-
In the main, we created 4 objects of class Student as stu1, stu2, stu3, and stu4 and verified that count and rollno are the same as no. of objects.
Example
// C++ program to Count the number of objects
// using the Static member function
#include <iostream>
using namespace std;
class Student {
public:
int rollno;
static int count;
public:
Student(){
rollCall();
rollno=count;
}
~Student()
{ --count; }
static void rollCall(void){
cout <<endl<<"Student Count:" << ++count<< "\n"; //object count
}
};
int Student::count;
int main(){
Student stu1;
cout<<"Student 1: Roll No:"<<stu1.rollno;
Student stu2;
cout<<"Student 2: Roll No:"<<stu2.rollno;
Student stu3;
cout<<"Student 3: Roll No:"<<stu3.rollno;
Student stu4;
cout<<"Student 4: Roll No:"<<stu4.rollno;
return 0;
}
Output
If we run the above code it will generate the following output ?
Student Count:1 Student 1: Roll No:1 Student Count:2 Student 2: Roll No:2 Student Count:3 Student 3: Roll No:3 Student Count:4 Student 4: Roll No:4