Solved

Loading an array of Persistent pointers from a stream

Posted on 2004-04-12
8
326 Views
Last Modified: 2008-03-06
This may be better off in the c++ thread but I think it relates to all object-orientated languages.

class Stream;
//Implementation isn't important just realize it supports reading and writing of all primitive types and a few higher level objects such as strings, etc.

class Persistent
{
public:
  Persistent();
  virtual ~Persistent();

  virtual void saveToStream(Stream& s);
  virtual void loadFromStream(Stream& s);
};

For those who aren't familar with the term persistent it basically means that it is a class that knows how to read and write it self to a stream.  Again implementation of this class isn't really all that important.  Notice that it implements virtual methods for saving a loading an instance of this class to a stream.

class C1 : public Persistent
{
public:
  C1();
  ~C1();

  virtual void saveToStream(Stream& s);
  virtual void loadFromStream(Stream& s);
};

Notice that class is a derived class from the Persistent class which provides its own virtual methods for saving and loading information to a stream.

Consider the following 2 examples which work just fine:

Example 1:
C1 myArray[10];
//initialize all C1 class instances with whatever not important.

Stream s;
//save the data to the stream
for(int i = 0; i < 10; i++)
  myArray[i].saveToStream(s);
s.setPosition(0); // set the stream back to the beginning
for(int i = 0; i < 10; i++)
  myArray[i].loadFromStream(s);

Example 2:
C1* myArray[10];
//initialize all C1 class instances with whatever not important and make sure the pointers are created.

Stream s;
//save the data to the stream
for(int i = 0; i < 10; i++)
  myArray[i]->saveToStream(s);
s.setPosition(0); // set the stream back to the beginning
for(int i = 0; i < 10; i++)
  myArray[i]->loadFromStream(s);

Both examples working flawlessly.


Now for the BIG QUESTION!!!
lets say I have a class C2 defined as

class C2 : public Persistent
{
public:
  C2();
  ~C2();

  virtual void saveToStream(Stream& s);
  virtual void loadFromStream(Stream& s);
};

and I have an array defined as such
Persistent* myArray[10];

myArray now holds pointers to class instances of Persistent or any class instance which has publicly derived from the class Persistent.

Saving data is no big deal
for(int i = 0; i < 10; i++)
  myArray[i]->saveToStream(s);

Well maybe saving data is no big deal I'll get back to that in a second.
Now how would I go about loading in myArray from a stream?  The stream data may be instance of C1 or instance of C2.

One possible solution I came up with is to have a const static datameber such as class_ID and do this

//save data
for(int i = 0; i < 10; i++)
{
  s << myArray[i]->class_ID;
  myArray[i]->saveToStream(s);
}

//load data
for(int i = 0; i < 10; i++)
{
  int class_id;
  s >> class_id;
  if(class_id == C1::class_id)
  {
    delete myArray[i];
    myArray[i] = new C1();
    myArray[i]->loadFromStream(s);
  }
  else if(class_id == C2::class_id)
  {
    delete myArray[i];
    myArray[i] = new C2();
    myArray[i]->loadFromStream(s);
  }
}

I don't really like this approach.  For each new decedent of Persistent I have to create a const static class_id.  And I have to make sure that no other classes that decedend from Persistent use this class_id.

I know this is an extremly difficult question so I will reward 500 points to all people who can provide an elegant solution to this problem.  Something that would require little maintenace of code.  That is I don't want to go and look through all my classes that decend from Persistent and make sure they don't have the same class_id as a new class that I am making and assign a different class_id.

a class_id may not is more than likely not an elegant way of solving this problem.  I'm thinking a template class or some sort of class factory may be more eligant but don't really know where to start.  Just throwing out some ideas.
0
Comment
Question by:PerryDK
8 Comments
 
LVL 4

Expert Comment

by:bkfirebird
ID: 10809430
Hi Perry,
I havent tried it myself, but in case you are using MFC ..... you can derive your class from CObject and it will work like serialized objects in java .
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccore98/HTML/_core_serialization.3a_.serializing_an_object.asp

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vcmfc98/html/_mfcnotes_tn002.asp

HTH
0
 
LVL 4

Expert Comment

by:bkfirebird
ID: 10809442
also check out s11n ... http://s11n.net/s11n/
0
 
LVL 4

Author Comment

by:PerryDK
ID: 10809609
I am not using MFC.  I am using Borland C++ Builder...but the answer to this question should be ANSI C++ compliant.  I want it to be a portable solution.
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 4

Accepted Solution

by:
YuriPutivsky earned 250 total points
ID: 10809942
You can use RTTI, which is a part of ANSI C++.
Instead of saving some artificial IDs, simply save type_info information like
const type_info& tinfo = typeid(this);
s << tinfo.name();

When you load from stream, check name and if it doesn't match the current object then call the base function like
class C : public Persistent
{
....
virtual void saveToStream(Stream& s)
{
const type_info& tinfo = typeid(this);
s << tinfo.name();
// save members
s << member;
}
virtual void loadFromStream(Stream& s)
{
const type_info& tinfo = typeid(this);
char buf[256]; // can be done more safely
s >> buf;
if (strcmp(buf,  tinfo.name())) // call base function
  Persistent::loadFromStream(s); // base function even can throw exeption in case of wrong type
else // exact match
 s >> member;
}
private:
int member;
};

0
 
LVL 4

Expert Comment

by:bkfirebird
ID: 10809996
i was thinking on the same lines ie using rtti , but i am not sure how you can call loadFromStream from the base class
0
 
LVL 15

Assisted Solution

by:efn
efn earned 250 total points
ID: 10810083
Every time I have confronted this problem, I have ended up using a class ID.  The class of the object is information that has to go into the stream and come out of the stream somehow and the class ID is a straightforward implementation technique for doing that.  I agree it's not pretty, but I doubt that you can do better.  You could wrap the process in a factory at the receiving end, but that just hides it, it doesn't change it.  If you maintain the class ID list in Persistent, you have only one place to look and change when you want to add a new derived class, but of course, it's not appealing for Persistent to have to know about all of its descendants.

--efn
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

This is about my first experience with programming Arduino.
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now