Write a program to count the instances of a class.
#include<iostream> using namespace std; class A { public: static int count; A() { cout << "Constructor" << endl; count++; } ~A() { cout << "Destructor" << endl; } }; int A :: count = 0; void fun() { A ob; } int main() { char op; cout << "Enter Y or y to create another object \n"; cin >> op; while((op == 'y') || (op == 'Y')) { fun(); cout << "Enter Y or y to create another object \n"; cin >> op; } cout << "Total number of object creation = " << A::count << endl ; return 0; }
Output
Enter Y or y to create another object y Constructor Destructor Enter Y or y to create another object y Constructor Destructor Enter Y or y to create another object y Constructor Destructor Enter Y or y to create another object y Constructor Destructor Enter Y or y to create another object n Total number of object creation = 4