The "incomplete type" error will be because you haven't included <fstream>
to get the definition of ofstream
.
The first won't work because you're trying to assign a pointer (returned by new
) to an object. In most cases, you would assign an object instead; but unfortunately streams aren't assignable, even by moving.
The second would work (once ofstream
has been defined), but is a bad idea since you now have a raw pointer to a dynamically allocated resource. You're quite likely not to delete it correctly, giving memory leaks or other problems.
This can be mitigated by using a smart pointer rather than a raw pointer; but in the case of ofstream
, you can simply leave it closed if you don't have a file to open:
std::ofstream file1;
if(hasFile1) {
file1.open(fileName1);
}
Also, beware that you're not initialising hasFile1
properly; and that you can't usually compare C-style strings using ==
. You want something more like
bool hasFile1 = (fileName1[0] != '\0');
or, if you change the file name arguments to the more friendly std::string
bool hasFile1 = !fileName1.empty();