I just have some general questions when it comes to C++ mainly focused on classes
1. When it comes to instantiating a class is there something like a static initializer? Or would it be better to have a static variable(s) and a corresponding flag to say whether or not the variables are ready to use?
2. Is it "bad" to throw exceptions in the constructor or should I use a 2 step initialization process? Example: I have TruckModel class and when I create a new instance I load in the mesh that this truck model uses. I throw an exception if the file cannot be found because I need the truck mesh in order to continue. This all happens within the TruckModel constructor
3. I am currently throwing some exceptions when critical errors happen and I guess exceptions do not work in the way I would expect. I sort of expect the program to come to screeching hault and fully stop execution, but it continues on if you just say to "continue" in the debugger. Simplified example:
#include <iostream>
int main()
{
int count = 0;
while (true)
{
//Exception is thrown and there is no attempt to catch it
//Debugger says the exception occurs and complains, but I can carry on with my program like normal if I just ignore the complaints and keep stepping through until I come back to this point
if (count == 10)
throw std::exception("Something went wrong...");
std::cout << "Count:" << count << std::endl;
++count;
}
std::cout << "COMPLETE!" << std::endl;
}
4. Is it possible to hide a destructor from being directly called? I have classes that have a Release method to clean up various pointer resources used by the class instance. The destructor of the class does not call my Release method as that would free the resources prematurely in some cases. Example:
ResourceItem *ResourceCreator::createResourceItem(UINT size)
{
ResourceItem resourceItem;
system->CreateResourceItem(size, &resourceItem.dataPointer);
resourceItems.push_back(resourceItem);
return &resourceItems.back();
}
//resourceItem goes out of scope here. A call to the Release method in the destructor would free resources that should not be freed yet
5. When it comes to variables should I always be giving them a value in the constructor? I have noticed for pointer variables that they do not have NULL or nullptr as there value by default. So it has me wondering if all values are or could be garbage values at there start? Example:
class MyClass {
public:
//Would expect this to be 0 by default. Not sure if I should set this to 0 in constructor because of potential default garbage value
int count;
//Would expect this to be NULL or nullptr, but have seen random garbage value as the default
OtherObject *otherObj;
}