Y
ypjofficial
Hello All,
I am defining a class with one virtual function and storing its first 4
bytes ie. the address of the virtual function table to a file.I am
again rereading the file in the same program and calling the virtual
function.The function gets called nicely but it shows the junk values
for the member variables of the class of which the function is a
member..below is the code
//Program start
#include "iostream.h"
#include "fstream.h"
struct vptrtable
{
void (*fptr)();
};
class one
{
int i;
public:
one(){i = 9;
}
virtual void fun()
{
cout<<"i is "<<i<<"\ninside fun\n";
}
};
int main()
{
one o;
fstream f("c:\\1.txt",ios:ut);
//storing the vptr into the file
f.write((char*)&o,sizeof(int));
f.close();
int p=0;
fstream g("c:\\1.txt",ios::in);
//getting back the fptr from the file
g.read((char*)&p,sizeof(int));
vptrtable * v=(vptrtable*)p;
//calling the function.
v->fptr();
return 1;
}
//Program end
The output is
i is 1769172585
inside fun
i should be 9..but the function is getting called nicely..
what is going wrong here?
If it has to fail then why the function is getting called correctly?
Thanks and Regards,
Yogesh Joshi
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
I am defining a class with one virtual function and storing its first 4
bytes ie. the address of the virtual function table to a file.I am
again rereading the file in the same program and calling the virtual
function.The function gets called nicely but it shows the junk values
for the member variables of the class of which the function is a
member..below is the code
//Program start
#include "iostream.h"
#include "fstream.h"
struct vptrtable
{
void (*fptr)();
};
class one
{
int i;
public:
one(){i = 9;
}
virtual void fun()
{
cout<<"i is "<<i<<"\ninside fun\n";
}
};
int main()
{
one o;
fstream f("c:\\1.txt",ios:ut);
//storing the vptr into the file
f.write((char*)&o,sizeof(int));
f.close();
int p=0;
fstream g("c:\\1.txt",ios::in);
//getting back the fptr from the file
g.read((char*)&p,sizeof(int));
vptrtable * v=(vptrtable*)p;
//calling the function.
v->fptr();
return 1;
}
//Program end
The output is
i is 1769172585
inside fun
i should be 9..but the function is getting called nicely..
what is going wrong here?
If it has to fail then why the function is getting called correctly?
Thanks and Regards,
Yogesh Joshi
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]