I was reading Thinking in C++, and found this piece of code:
//: C06:Persist1.cpp
// Simple persistence with MI
#include <iostream>
#include <fstream>
using namespace std;
class Persistent {
int objSize; // Size of stored object
public:
Persistent(int sz) : objSize(sz) {}
void write(ostream& out) const {
out.write((char*)this, objSize);
}
void read(istream& in) {
in.read((char*)this, objSize);
}
};
class Data {
float f[3];
public:
Data(float f0 = 0.0, float f1 = 0.0,
float f2 = 0.0) {
f[0] = f0;
f[1] = f1;
f[2] = f2;
}
void print(const char* msg = "") const {
if(*msg) cout << msg << " ";
for(int i = 0; i < 3; i++)
cout << "f[" << i << "] = "
<< f[i] << endl;
}
};
class WData1 : public Persistent, public Data {
public:
WData1(float f0 = 0.0, float f1 = 0.0,
float f2 = 0.0) : Data(f0, f1, f2),
Persistent(sizeof(WData1)) {
cout<<"size of w1 "<<sizeof(WData1)<<endl;
}
};
class WData2 : public Data, public Persistent {
public:
WData2(float f0 = 0.0, float f1 = 0.0,
float f2 = 0.0) : Data(f0, f1, f2),
Persistent(sizeof(WData2)) {
cout<<"size of w2 "<<sizeof(WData2)<<endl;
}
};
int main() {
{
ofstream f1("f1.dat"), f2("f2.dat"),f3("f3.dat"), f4("f4.dat");
WData1 d1(1.1, 2.2, 3.3);
WData2 d2(4.4, 5.5, 6.6);
WData1 d3(1.1, 2.2, 3.3);
WData2 d4(4.4, 5.5, 6.6);
d1.print("d1 before storage");
d2.print("d2 before storage");
d3.print("d3 before storage");
d4.print("d4 before storage");
d1.write(f1);
d2.write(f2);
d3.write(f3);
d4.write(f4);
} // Closes files
ifstream f1("f1.dat"), f2("f2.dat"),f3("f3.dat"), f4("f4.dat");
WData1 d1;
WData2 d2;
WData1 d3;
WData2 d4;
d1.read(f1);
d2.read(f2);
d3.read(f3);
d4.read(f4);
d1.print("d1 before storage");
d2.print("d2 before storage");
d3.print("d3 before storage");
d4.print("d4 before storage");
} ///:~
It produces unexpected output: Objects of class WData1 are persisted correctly, but objects of WData2 aren't. While trying to find the source of problem, and possible fix, I found out, that problem is only in reading WData2 (its stored correctly in the file). To make this code work as intended, I had to change inheritance order from:
WData2 : public Data, public Persistent{...
to
WData2 : public Persistent, public Data{...
I'm curious why inheritance order makes difference in this case. Shouldn't it make no difference?