Using ifstream as a constructor parameter

Jan 30, 2013 at 1:42am
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 Jan 30, 2013 at 1:43am
Jan 30, 2013 at 1:51am
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/
Jan 30, 2013 at 1:52am
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 Jan 30, 2013 at 1:53am
Jan 30, 2013 at 1:54am
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 Jan 30, 2013 at 1:55am
Topic archived. No new replies allowed.