1

I learned C and a tiny bit of C++ in school, and when going back and trying to reteach myself C++ for work, it is very hard because almost all of what I remember from class is C, which is apparently bad to use in C++ (eg: fscanf, malloc). one thing that confuses me is classes and constructors. here is an example that confuses me immensely.

why does this work:

fstream a;
a.open("foo.txt", std::fstream::in | std::fstream::out);

but:

fstream a();
a.open("foo.txt", std::fstream::in | std::fstream::out);

not work? isn't calling a default constructor the same as declaring an instance of a type?

  • 1
    Use a better compiler or more warnings: *warning: empty parentheses interpreted as a function declaration* – chris Jul 20 '15 at 04:29

1 Answers1

2

fstream a(); declares a function called a that takes nothing and returns an fstream object. The compiler can't tell the difference between a declaration of an object instance with empty parentheses and a function declaration, so it assumes that it is a function, but if you have the right warning level turned on it will warn about it.

Effective C++ by Scott Meyers covers common gotchas like this. I would recommend you reading it to save yourself hours of head scratching.

Dominique McDonnell
  • 2,510
  • 16
  • 25