+ 11
How can I write a c++ program to count the number of objects created?
6 Respostas
+ 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
}
+ 8
Thank you Nikhil Dhama best solution though
+ 3
welcome ☺️
+ 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;
}
0
56667899
0
5 6 7 8 9 5 6