is there any way to make all derived classes count their instances?How (write code in one of C++, C#, Java)?
Imagine I\'ve got access to the root class (e.g. object), an
I would use a template. This is in C++, by the way.
template class object {
private:
static int count;
public:
object() { count++; }
object(const object&) { count++; }
~object() { count--; }
static int GetCount() { return count; }
};
template int object::count = 0;
RTTI solution:
class object {
static std::map counts;
public:
object() { counts[typeid(*this).name()]++; }
object(const object&) { counts[typeid(*this).name()]++; }
~object() { counts[typeid(*this).name()]--; }
template int GetObjectsOfType() {
return counts[typeid(T).name()];
}
int GetObjectsOfType(std::string type) {
return counts[type];
}
};
std::map object::counts;
RTTI is less invasive and allows run-time selection of the type to be queried, but the template has far less overhead and you can use it to count every derived class individually, whereas RTTI can only count the most derived classes individually.