Copy Constructor

I can open ifstream files from my main() that is not trivial. But when I try opening an ifstream file using a function I am having a problem reading from the ifstream file that I created. My instructor is saying that I can only return a pointer or a reference to one and I thought that is what I am doing.

This is the bare bone program so I could test if I can read from the ifstream file. How can I see the ifstream file created by the function to be seen from the main?

int main()
{
ifstream TestFile;
char buffer[128];
OpenFile(TEST_FILE, TestFile);

TestFile.getline(buffer, 128);
return(EXIT_SUCCESS);
}

void OpenFile(const char *TEST_FILE, ifstream &inFile)
{
//ifstream inFile(TEST_FILE, ios::in); //1. If I do this it says I have a
//redefinition of the formal parameter
inFile(TEST_FILE, ios::in); //2. if I do this is says call of a class type
//without appropriate operator()
//or conversion functions to pointer-to-function type
ifstream aFile(TEST_FILE, ios::in); // 3. if I do this this will compile but
// 1 cannot make infile = afile

if (!inFile.is_open())
{
}
//inFile = aFile; //note 4. This gives me an error saying I do not
//have access to private member
// was added in conjunction with note 3
}
Have you tried:
inFile.open(TEST_FILE, ios::in);
in the OpenFile function?
void OpenFile(const char *TEST_FILE, ifstream &inFile)
{
//ifstream inFile(TEST_FILE, ios::in); //1. If I do this it says I have a
//redefinition of the formal parameter

You may not redefine parameter in the outermost block of a function andthe compiler say about this prohibition.


inFile(TEST_FILE, ios::in); //2. if I do this is says call of a class type
//without appropriate operator()
//or conversion functions to pointer-to-function type

It is syntax of calling operator function. This class has no such an operator.


ifstream aFile(TEST_FILE, ios::in); // 3. if I do this this will compile but
// 1 cannot make infile = afile


Here you create a new ifstream object. iit is not what you wanted.

if (!inFile.is_open())
{
}
//inFile = aFile; //note 4. This gives me an error saying I do not
//have access to private member
// was added in conjunction with note 3
}

You may not assign one stream to another.


All what you need is to use member function open. For example

inFile.open( TEST_FILE );
Amol, Vlad,

inFile.open(TEST_FILE, ios::in);
This is your solution and it worked, thank you. what I don't understand is why this two do not work.

ifstream inFile(TEST_FILE, ios::in);
or
inFile(TEST_FILE, ios::in);

Ed
ifstream inFile(TEST_FILE, ios::in)
This creates an instance of ifstream.
inFile(TEST_FILE, ios::in)
This is a function call to the function inFile, with parameters TEST_FILE and ios::in.
Last edited on
Topic archived. No new replies allowed.