In the thread people suggest to instantiate the class "ifstream": std::ifstream inputSteram( "list.txt" );
where:
* list.txt is the file where information will be read
* inputStream is the name of object instantiated
Furthermore in this thread people write things like
1 2 3 4 5
if (!inputStream){
cout << "could not open input file\n";
return 1;
}
and
1 2 3 4 5
// check everything went ok
if (!inputStream){
cout << "error reading 10 numbers from file into array\n";
return 1;
}
Does it mean that there was an error while initializing the object?
Is this a default cpp behavior? I mean setting the object to null when the initialization failed.
The if (!inputStream) has !, the operator!. There is global operator! that does logical not for a bool value. In this case the inputStream is not converted into bool, because the stream has a more specific operator!: http://www.cplusplus.com/reference/ios/ios/operator_not/
A fstream is more than just a handle to a file in disk. It has other attributes, like those failbit and badbit. The stream object as a whole is never "null".
The fstream is never incorrectly initialized. It has always a consistent state. A file error is a "valid state" too.
Here is incorrect initialization:
1 2 3 4 5 6
class Foo {
int count; // size of char array bar
char * bar;
public:
Foo( int s ) : bar( new[s] ) {}
};
The count should match the size of the allocated array, but the constructor does nothing to ensure that. However, a Foo object will not be null, just inconsistent. The users of Foos might notice that, or not. If their code depends on count always being the size of the array, ...
In this case the inputStream is not converted into bool, because the stream has a more specific operator!
I got it! I wonder how is the function definition of this overloaded operator. I'm curious...
Regarding the example of incorrect initialization:
I understand that this is the parameterized constructor: Foo( int s ) : bar( new[s] )
The value of "bar" is set via initialisation list. However an "int s" is given as an input argument but I guess it is never set to "count" and this is the problem.
However I wonder if in this case can an implicit conversion take place for "int s".
Is there an implicit conversion?
I wonder if in this case can an implicit conversion take place for "int s".
Implicit conversion to what?
There is a trivial implicit conversion when new[s] is called. s is implicitly converted from an int to size_t. Other than that there are no other conversions taking place.
count requires an explicit initialization either through the initialization list or via an explicit assignment. The compiler has no clue you meant to initialize count. However, most compilers will give you a warning if you try to utilize an uninitialized variable.