I was practicing working with classes and the static property included with them and came up with a simple ID counter and max number list. I also added a quick debug error throw
if it goes over. Here's what I came up with:
#include <iostream>
// A class that has static variables to save information for the ID's of its instances.
class HoldIdentity{
private:
static int const maxInstances = 20;
static int created; // = 0; error
public:
static int getMax(){
return maxInstances;
}
// A static function that will return an array on the heap of every /possible/ remaining Identity Holder.
static HoldIdentity* const createAll(){
int length = maxInstances - created;
HoldIdentity*JAM = new HoldIdentity[maxInstances - created];
for (int i = 0; created < maxInstances; JAM[i++]=HoldIdentity());
return JAM;
};
private:
int id;
public:
HoldIdentity(){
id = created++;
if (created > maxInstances){
created--;
std::string error = "To many instances!";
throw (error);
}
}
// Destructor displays the id.
~HoldIdentity(){
displayID();
}
void displayID() const{
std::cout << "my id:" << id << std::endl;
}
};
//int HoldIdentity::created = 0;
int main(){
using namespace std;
HoldIdentity numba1{};
numba1.displayID();
HoldIdentity *allInstances = HoldIdentity::createAll();
// because creating more than the max causes an error.
// I suppose I should have put all prior code in here as well.
try{
HoldIdentity numbaPast{};
HoldIdentity numbaPast2{};
HoldIdentity numbaPast3{};
}
catch (...){
// I think I could have used a string to retrieve the message?
cout << " too many instances! ";
}
// free array from the heap.
delete[] allInstances;
system("pause");
return 0;
}
edit: Is there any little bit of code here that could be improved? I've only just started working on C++(again) this week so I'm sure there's many alternatives. But specifically if my own code for determining and handling IDS are bad. Besides that, is my error handling a good practice?