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.
#include <iostream>
#include <stdio.h>
usingnamespace std;
class base
{
public:
virtualint size() = 0;
virtualvoid* 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;
}