Re: Difference between struct and class and pointer to member data
On Sep 9, 3:47 pm, Pep <pepaltavi...@yahoo.co.uk> wrote:
Think it is about time I got this straight in my head, with
the help of you guys of course ;)
So a struct is a collection of data members as is a class,
where a class default scope is private and a struct default
scope is public. All well and good so far.
More practically, there aren't really struct's in C++. Both
class and struct keywords defined classes.
Note too that they can be used more or less interchangeably:
class Toto ; // foreward declaration
If I send the address of a struct or class to a function
within my program everything is well and good, obviously all
of the class/ struct, i.e. the members, methods and vtable
exist in my program.
That's the compiler's problem, not yours.
Now here is the point I get a little fuzzy, what happens if I
want to serialize the struct/class.
You have to write the code to do it.
Assuming I send the address of the struct/ class and it's
size() as parameters to my serialize function, I can
effectively write the size() number of bytes from the address
parameter to a file.
You can, but it doesn't necessarily mean anything. Except for a
few degenerate cases, you won't be able to reliably reread the
What happens with the methods and vtable of a struct/class
when you serialize it?
What do you want to happen to them?
The member functions are just that---functions, and are compiled
into the application. You can't write them to disk, nor reread
them; there's practically no way of serializing them. In most
implementations, the vtable is also part of "code"; all that the
class contains is a pointer to it.
When serializing data (regardless of the type of data), you need
to know the type in order to reread it successfully. This
knowledge can come from the structure of the file (at this
location in the file, there is always a Toto), or by writing
some sort of type identifier in front of the data, and reading
I know that I can easily allocate a region of memory and cast
it to a struct/class and effectively use it as an instantiated
instance of the struct/class.
No you can't. That's undefined behavior, and typically doesn't
So I suspect the obvious answer is that the methods and vtable
are discarded and reapplied when the memory region when cast
against a struct/class.
Presumably, the only way a struct/class can be deserialized is
by a function that knows the declaration of the struct/class?
Again, that's true for any type, not just class types.
So is what I outlined correct in terms of the c++ standard or
only for certain c++ compilers that may have extended things?
It's completely false.