+ 11

How can I write a c++ program to count the number of objects created?

1st Jul 2018, 6:00 AM
thealoneprogrammer
thealoneprogrammer - avatar
6 ответов
+ 20
declare a static variable inside the class, and upgrade its value inside the constructor definition, you can access this variable using class name. Edit: example- class A { static int count; A() { count++; } /* *rest body of the class */ /* include count++ in every constructors, in case you have defined parameterized or copy constructors also */ }; main() { A obj1; cout<< A::count; //output :- 1 A obj2; cout<< A::count; // output :- 2 }
1st Jul 2018, 6:11 AM
Nikhil Dhama
Nikhil Dhama - avatar
+ 8
Thank you Nikhil Dhama best solution though
1st Jul 2018, 6:39 AM
thealoneprogrammer
thealoneprogrammer - avatar
+ 3
welcome ☺️
1st Jul 2018, 6:49 AM
Nikhil Dhama
Nikhil Dhama - avatar
+ 3
Tq Nikhil Dhama 😊👍🏻 #include<iostream> using namespace std; class A { public: static int count; public: A() { count++; } }; int A::count; int main() { A obj1,obj2,obj3,obj4; cout<<"no of objects created= "; cout<<A::count; }
16th May 2021, 6:50 AM
Anushree
Anushree - avatar
0
56667899
21st Apr 2024, 5:44 PM
Aryan
Aryan - avatar
0
5 6 7 8 9 5 6
21st Apr 2024, 5:44 PM
Aryan
Aryan - avatar