Using ifstream as a constructor parameter

I'm trying to pass an reference of the object ifstream to my constructor as such:

1
2
3
4
5
6
7
// myClass.cpp
int main(){
ifstream file;

myClass classobj = myClass(file);

}


I am defining the constructor as follows, in myClass.cpp:

1
2
3
4
myClass::myClass(ifstream &file){

// do stuff
}


I get the error of "No overloaded function of myClass::myClass matches the specified type."

Also, when I build the program, it tells me "syntax error: identifier 'ifstream'"

Also, I made sure I included this:
#include <iostream>
#include <fstream>
#include <sstream>


What am I doing wrong? How can I pass an ifstream reference to my constructor?
Last edited on
ifstream and all other STL functions and classes are in namespace called std. To access them, you need to use std::<whatever you want here> (eg std::ifstream).

So then your constructor would look like this:
1
2
3
myClass::myClass (std::ifstream& file) {
// do stuff here
}


and your main would look like this:
1
2
3
4
5
6
7
int main () {
std::ifstream file;

// Note that this calls the constructor directly, rather than calling it and then calling the copy constructor
myClass classObj (file);

}


I hope this helped!

also, more on namespaces here:
http://cplusplus.com/doc/tutorial/namespaces/
does it matter if i've also put "include namespace std" at the top?

EDIT: Thanks for pointing that out, actually. I had the include statement at the top of my .cpp file but not my header file.
Last edited on
it should say using namespace std;.

that will the same thing as what I described above, eg

1
2
3
4
#include <iostream>
using namespace std;

ifstream file;


does the same thing as
1
2
3
#include <iostream>

std::ifstream file;


(edit):

the article i put a link to describes it much better than I have
Last edited on
Topic archived. No new replies allowed.