serialization of object with pure virtual function

All,

I have a basic question. I hope some one could help me with a better implementation of what I am trying to do.

Basically, I have a bunch of child classes that inherit from a base class with virtual function. I would like to write a connection class to send the messages. The connection class only know about the base class. The connection need to know where is the start of the serialized data and how much to send.

Here is my current idea. I don't feel comfortable with it. I hope some one can help me with a more elegant way to do this.


thanks,
ted

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66


#include <iostream>
#include <stdio.h>

using namespace std;

class base
{
   public:
      virtual int size() = 0;
      virtual void* getStartOfData() =0;
};

class child: public base
{
   public:
      child( int v ):data(v){};

      int size(){ return 4; };
      void* getStartOfData(){ return (void*)&data; };

   private:
      int data;
};

class tcpConnection
{
   public:
      void write( void*, int size ){};
};

int main()
{ 
   base* object = new child( 5 ) ; 

   // this should print 8 to reflect the vtable information
   cout << "Hello: size =" << sizeof( child ) << endl;

   // this should print 4
   cout << "Hello: size =" << object->size() << endl;

   int* ptr = (int*)object;
   printf(" %X \n", ptr[0] ); // print vtable info
   printf(" %X \n", ptr[1] ); // print value of data

   tcpConnection con;
   // I would like to use it for serialization purpose such as 
   // sending over tcp

   // older practices which won't work 
   con.write( (void*)object, sizeof( child ) );

   // this would work 
   // I don't need to know what child type it is,
   // I have all the information for writing
   con.write( (void*) object->getStartOfData(), object->size() ) ;

   // is there a more elegant way to do this? 
   

   // do memory clean up here
   return 0;
}

Last edited on
Topic archived. No new replies allowed.