incanus86 incanus86 - 1 year ago 90
C++ Question

C++11 error no match for call to Ifstream outside main

I'm brand new to c++, trying to learn it on my own.

I've found several questions related to this but none of them have really answered it. I've enabled c++11 so ifstream should accept a std::string as far as I can tell. I've also tried this in Visual Studio, CLion, and Eclipse Neon with the exact same results.

I've also checked the value of __cplusplus at runtime and I know it is set to 201103, which is required for the overloading of the constructor.

Essentially if I use std::ifstream in the main function using a std::string I have no problems. On the other hand if I try to pass it to a another class that in another file I receive this error in Eclipse and Clion:

"error: no match for call to '(std::ifstream {aka std::basic_ifstream}) (std::__cxx11::string&)' infile(filename);"

And this error in Visual Studio:
"error C2064: term does not evaluate to a function taking 1 arguments"

Both errors point to the same line as indicated in the code block below. I would like to know what I'm doing wrong as I'd like to use ifstream inside of the class.

// main.cpp
#include test.h
int main() {
std::string name("test.txt");
TestClass test (name);
std::ifstream testfile(name);
return 0;

// test.h
#include <fstream>
class TestClass{
std::ifstream infile;
TestClass(std::string filename); // have also tried with std::string& filename

// test.cpp
TestClass::TestClass(std::string filename){ // again have tried using string&
infile(filename); /** ERROR **/

Answer Source

std::ifstream doesn't provide a operator()(std::string) overload. Hence


in the constructor body fails to compile.

There is a constructor taking a const std::string& though, that can be used in your classes member initializer list:

TestClass::TestClass(std::string filename) : infile(filename) {
    // Omit that completely: infile(filename);  /** ERROR **/
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download