Link to home
Start Free TrialLog in
Avatar of dotand
dotand

asked on

Advanced C++: rtti and serialization (properties)

Hi everybody,

I am trying to build a data structure ressembling a registry for my C++ application ( a client and server implementing the RTSP protocol).
Is it possible to include the name of the class as a strign and have an object of that type made (I think java can do it)?
Also , is it possible to serialize objects in C++ (and for lack of a better option use properties liek in Java)?

Thanks for your help.
Dotand
ASKER CERTIFIED SOLUTION
Avatar of nietod
nietod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of nietod
nietod

That allows you to (1) determine the type of the object (if it has a virtual function and (2) recreate a default constructed object fo that type (if that type was registered).  These two features are necessary for serialization, but are not enough to impliment it.  You still need a way to write out the object informaiton and a way to read it back into an object after it was created with the create procedure.  In general this is hard to do, but if you are willing to impose one more limitation, it becomes considerably easier.

Can you require that all the objects be in a single class hierarchy?  There are many advantages to this and this is the way that serialization in C++ is ussually handled.

If you have all the objects in a single class hierarchy, then you can add two virtual procedures to the class heirarchy (starting with the base class).  You add a procedure to write the class data out to a stream and another to read it back in from a stream.  Ever class in the hierarchy that has non-static data members must implement these two procedures.  (And in each of these procedures they must call their immediate base class's procedure to have it read/write its data and so on up the class hierarchy).  

Now the create functions will still create derived objects, but they will return pointers whose type is a pointer to the base class. (important later)

To write out an object, you use RTTI  to get the object;'s class name and write that to a stream, then you call the object's virtual write procedure and it will write all the object's data to the stream.

To create an object from a stream, you read the object's class name.  Then you look up its create pointer and call the create procedure.  This returns a pointer whose types is the base class type, however, it really points to a derived class.  Next you call the virtual read procedure and it reads in the object's data.

Let me know if you have questions.