<yp*********@indiatimes.comwrote in message
news:11**********************@i42g2000cwa.googlegr oups.com...
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.
No offence, but I hope you are well aware of what you are trying to do.
I also hope you already know there has been some talks about those who
write pointers to disk and read them back (first thing I remember is
Herb's talks).
Without looking at the piece of code below, I am guessing that you
forgot "this" pointer and read a junk memory, fortunately, somewhere
that does not cause a page fault (i.e. access violation, segfault).
You need correct "this" pointer to play with (super-fragile) vtable
properly. However, those extreme tricks are not reputable as far as
standard is concerned, as standard does not define vtable layout or
internal implementation details. In multiple-inheritance cases, vtable
layout may become extremely complex and even brings experts down their
knees.
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::out);
//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
I see no (run-time) polymorphism here. In fact, I think I have
understood what you want, but the term "vtable" is usually used with
polymorphism.
Anyway, one short part of the answer to your question is (IMHO);
you jump to code, but you do not have a correct object and this pointer,
so the "i" is loaded with garbage. "this" pointer is required to find
correct address of member "i" (well, actually for virtual functions as
well) - it's about memory layout of the object.
If you derive a class from "class one" and call "fun" member function
polymorphically, your call will still go to one::fun rather than the
last override - and you will, of course, not haveany member of the class.
This is not portable, not standard, not good, too fragile, too evil (and
you have used it wrong).
Ismail
[ See
http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]