Help in writing a class to file and calling a constructor (fairly simple)
Hello!
I got one class named Hired and want to write the whole class into a file. But upon execution the program stops and ends without even create the file.
Also; how do I call the construtor that takes the INT paramter?.... Ex: Hired(int i = 1); does not seem to work, it still calls the Hired() that takes no parameters?!
The CLASS
Code:
class Hired
{
private:
int nr;
int ant_barn;
public:
Hired (int n)
{
cout << "Hired nr: (100-999)" << endl;
cin >> nr;
cout << "Ant barn: 0-20" << endl;
cin >> ant_barn;
}
Hired ()
{
cout << "\n\nWARNING 1: SHALL NOT RUN THIS CONSTRUCTOR\n\n";
}
void write_file(ofstream* out)
{
*out << nr;
*out << ant_barn << endl;
}
void display()
{
cout << "Nr: " << nr;
cout << "ant barn: " << ant_barn;
cout << endl << endl;
}
GLOBALS
Code:
//Globals
Hired* hired[100];
int lastused = 0;
The main program.
Code:
int main()
{
//Filling in at least one "hired" with data:
hired[lastused].Hired(lastused); //How do I call the Constructor that takes INT as a parameter in my class? SInce this line does not work!!
I've also tried switching the "." with ->, did not work
lastused = lastused + 1;
//To file
ofstream myfile("hired.dta", ios::out | ios::ate);
for (i = 1; i < lastused; i++)
{
hired[i]->write_file(&myfile); //Failure here or/and line below... I've also tried "hired[i].write_file(&myfile);
hired[i]->display();
}
myfile.close();
//To memory
Hired* a;
ifstream myfile2("hired.dta", ios::in);
if (myfile2) //Read data in to file
{
i = 0;
myfile2.read((char*) &a, sizeof(Hired));
while (!myfile2.eof() && lastused >= i)
{
myfile2.read((char*) &a, sizeof(Hired));
hired[i] = a;
++i;
hired[i]->display();
}
}
cout << "DONE";
return 0;
}
Marked the lines that I am stumbled at with red color.
How do I call the constructor in my class, when my "hired" is a pointer with array of type Hired.
PS: If I made the "hired" pointer array variable of no pointer type, this works, then I just switch "->" with ".". But I want to work with pointers now!
PS2: CodeBlocks editor, compiler GCC