file input-output and virtual functions
Aug 4, 2015 at 4:28pm UTC
Please, help with file output and input of objects. I have base class "firstbase", and its derivative "second". I try to output to file jbject of derivative class, and it seems to be OK. But after declaring functions of base class as virtual, file input is wrong. What am I doing wrong? Thank you.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
class basefirst
{
public :
virtual ~basefirst(){};
virtual void getdata();
virtual void putdata();
protected :
int a;
double b;
char cst[30];
};
void basefirst::getdata()
{
cout << "input integer number " ; cin >> a;
cout << "input float number " ; cin >> b;
cout << "input string " ; cin >> cst;
}
void basefirst::putdata()
{
cout << "integer number " << a << endl;
cout << "float number " << b << endl;
cout << "string " << cst << endl;
}
class second : public basefirst
{
public :
second(){}
void getdata();
void putdata();
private :
float d;
};
void second::getdata()
{
basefirst::getdata();
cout << "input once more float number " ; cin >> d;
}
void second::putdata()
{
basefirst::putdata();
cout << "once more float number " << d << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
second *bf1;
bf1 = new second;
bf1->getdata();
bf1->putdata();
ofstream ofile;
ofile.open("bfirst.txt" , ios::binary);
ofile.write(reinterpret_cast <char *>(bf1), sizeof (second));
ofile.close();
bf1 = new second;
ifstream ifile;
ifile.open("bfirst.txt" , ios::binary);
ifile.read(reinterpret_cast <char *>(bf1), sizeof (second));
(*bf1).putdata();
ifile.close();
system("pause" );
return 0;
}
Aug 4, 2015 at 8:48pm UTC
What is the expected output and what are you actually getting?
You have a memory leak, using new
on the same pointer twice without deleting it after the first use.
Topic archived. No new replies allowed.