Hey guys i'm having a lil trouble with object serialization.

student * s = new student("Mike",200014);
ofstream ofs("student.dat",ios_base::out | ios_base::binary);
ofs.write((char*)&s,sizeof(s));
ofs.close();

If student was a class with attributes studentName:string and studentNumber:int would the above code write the object pointed by s to the file student.dat ?

Serializing objects like that is not safe unless you can guarantee that the class in question is a POD type. In the best case for something like std::string, you'd end up writing addresses pointing to data rather than the data itself. The actual data would be lost and the addresses would be meaningless when deserializing.

You might consider using something like Boost::Serialization, or manually serializing by writing ToString() and FromString() methods in your class, then serializing the string data. Which is better really depends on your needs.

What deceptikon said. Writing good serialization code is not simple, and just writing an instance of a class (especially if it has pointer data, or virtual functions) will not work as you would expect. As he mentioned, you can use pre-packaged serializers such as provided by the boost library, or you can roll your own. Some years ago I wrote an object serialization package that handled arbitrarily complex structures into a TCL-based wire format for a distributed system. It was a LOT of work! So, do some Googling and find a package that will work for you instead of writing your own, would be my recommendation.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.