Constructor Exception
-
I'm still new to learning C++ (learned some of C# first) and having a hard time knowing what the preferred way to handle this situation is. I have a class that has a constructor that does some initialization work. If this initialization fails, I want to inform the program that this is not a valid object to use. I created my constructor to throw an exception as that is really the only way that I know how (since constructors can't return values). Now, in my program I am trying to create an object of my class so I put a try/catch block around it. This worked great until I realized that no code outside of the try/catch block would be able to use that object because it is out of scope. It appears that there is no good way to use global variables that has a constructor that throws an exception. So what is the normal procedure for this type of situation. Do you normally create a pointer to the object so that you can use the new keyword to create the object? If so, is there a way to prevent someone from creating an object and not a point to your class?
-
I'm still new to learning C++ (learned some of C# first) and having a hard time knowing what the preferred way to handle this situation is. I have a class that has a constructor that does some initialization work. If this initialization fails, I want to inform the program that this is not a valid object to use. I created my constructor to throw an exception as that is really the only way that I know how (since constructors can't return values). Now, in my program I am trying to create an object of my class so I put a try/catch block around it. This worked great until I realized that no code outside of the try/catch block would be able to use that object because it is out of scope. It appears that there is no good way to use global variables that has a constructor that throws an exception. So what is the normal procedure for this type of situation. Do you normally create a pointer to the object so that you can use the new keyword to create the object? If so, is there a way to prevent someone from creating an object and not a point to your class?
hpjchobbes wrote:
So what is the normal procedure for this type of situation. Do you normally create a pointer to the object so that you can use the new keyword to create the object?
Yes, that's what I'd do.
hpjchobbes wrote:
If so, is there a way to prevent someone from creating an object and not a point to your class?
Make the constructors private and add a static method that returns a newly allocated object:
class C
{
public:
static C* MakeNewC() { return new C; }
private:
C()
{
}
};int main()
{
C c; // This won't compile
C* pC = C::MakeNewC(); // This will compile
}HTH!!!
Java, Basic, who cares - it's all a bunch of tree-hugging hippy cr*p