Junior — Middle
How can a limit be set on the number of instances of a certain class?
sobes.tech AI
Answer from AI
To limit the number of instances of a class created in C++, you can use a static counter variable inside the class, which increments when an object is created and decrements when it is destroyed. The constructor checks whether the limit has been exceeded, and if necessary, throws an exception or otherwise prevents the creation of a new instance.
Example:
#include <stdexcept>
class LimitedInstances {
static int count;
static const int max_instances = 5;
public:
LimitedInstances() {
if (count >= max_instances) {
throw std::runtime_error("Instance limit exceeded");
}
++count;
}
~LimitedInstances() {
--count;
}
};
int LimitedInstances::count = 0;
Thus, attempting to create more than 5 objects will throw an exception.