In a class I am working with, the constructor creates an ofstream object (I know, I should accept a reference to one instead, but this is for educational purposes). I was thinking that, even if I provided defaults for a number of things related to the file, there are a number of places for this method to fail. What if the file is read only? What if the drive is full? What if yada yada... So instead of trying to resolve all those things, failing, and returning a partially initialized object, I thought it would be keen if there were a way to prevent the constructor from returning an object to the program.
Classic myClassic = Classic("output.txt");
inside the constructor...
1 2 3 4 5
if(!fout.isopen())
{
cerr << "NO SOUP FOR YOU! (No object either!)";
this.implode();
}
Does this kind of thing exist? I'm more curious than anything.
The singleton pattern could be used for something like that. You could implemented a static create/instance method that returns a pointer to a valid object or 0 upon failure.
1 2 3 4 5 6 7 8 9 10 11 12 13
class A
{
A() {}
public:
static A * create() { returnnew A(); }
};
//...
A * a = A::create();
if( a )
{
// valid
}
delete a;