Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a c++ class object

Tags:

c++

For Reading a class object (here "arts" is the name of an object). I have to follow the following code filin is a input and output stream.

filin.write((char*)&arts,sizeof(arts));
filin.read((char*)&arts,sizeof(arts));

Can you explain these.

  1. Why do we type caste by adding (char *) and why to a character pointer.

  2. Why add & symbol before arts?.

  3. why add sizeof(arts) at the end?.


1 Answers

Why do we type caste by adding (char *) and why to a character pointer.

char is a wrong name. It’s a lie – it should be called byte because that’s what it is: a byte. The read and write functions you’re using work on a byte buffer – this is to make them generic, i.e. work with arbitrary types (although that’s a also lie).

Why add & symbol before arts?

The & takes the memory address of an object. By writing (char*) &obj we are effectively getting (the address to) a byte buffer that is underlying a given object – in other words, the object’s representation in bytes.

why add sizeof(arts) at the end?.

sizeof(obj) tells us how large obj is in memory – i.e. how many bytes it takes up in the byte buffer. Given the start address (see previous point) and the size, we completely characterise an object’s physical existence in memory and we can use this to transfer an object from main memory into a file and vice versa.

However, as I’ve said before that’s kind of a lie. C++ actually has many types of objects which do not support this kind of copying their memory around, because these objects actually make assumptions about the memory they live in. In the simplest case they contain a pointer member which, after copying the byte representation of the object, still points to the old location and is thus no longer useful:

struct some_class {
    some_class* self;

    some_class() : self(this) { }
};

This class has a member – self – which points to itself. Copying an instance of this class bytewise would destroy this identity and render the object useless (after copying the self member of the copy would still point to the original, not the copy).

This kind of byte-wise copying is also called a shallow copy – as opposed to a deep copy which would copy the afore-mentioned pointer correctly.

The code you’ve shown is not generally safe in C++. In fact, there are even more issues with it than I’ve so far alluded to, and in most cases there are better alternatives for the (de)serialisation of objects.

like image 93
Konrad Rudolph Avatar answered Dec 02 '25 22:12

Konrad Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!