
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 Objects Using Static Member Function in C++
Here we will see how to count number of objects are created from a specific class using some static member functions. The static members are class properties, not the object properties. For a single class there will be only one instance for static members. No new members are created for each objects.
In this problem we are using one static counter variable to keep track the number of objects, then static member will be there to display the count value.
When a new object is created, so the constructor will be called. Inside the constructor, the count value is increased. Thus we can get the output.
Example
#include <iostream> using namespace std; class My_Class{ private: static int count; public: My_Class() { //in constructor increase the count value cout << "Calling Constructor" << endl; count++; } static int objCount() { return count; } }; int My_Class::count; main() { My_Class my_obj1, my_obj2, my_obj3; int cnt; cnt = My_Class::objCount(); cout << "Number of objects:" << cnt; }
Output
Calling Constructor Calling Constructor Calling Constructor Number of objects:3
Advertisements