views:

97

answers:

5

Hello, I have serialized a C++ object and I wish to allocate space for it, although I can't use the "new" operator, because I do not know the object's class. I tried using malloc(sizeof(object)), although trying to typecast the pointer to the type the serialized object is of, the program shut down. Where is the information about the object class stored?

class object
{
  public:
    virtual void somefunc();
    int someint;
};

class objectchild:public object
{
}

object *o=(object*)malloc(sizeof(objectchild));

cout << int(dynamic_cast<objectchild*>(o)) << endl;

This causes a program shutdown.

Thank you in advance.

+2  A: 

you should not mix C++ and C memory routes. dynamic_cast checks actual type of object. in your case you have raw memory casted to object *

Andrey
A: 

You need the following code

object *o = new objectchild;

to use dynamic_cast.

Alexey Malistov
A: 

You're trying to dynamic_cast a memory location with nothing in it. malloc has given you free space to place an object, but until the new() operator is called no object is there, so when dynamic_cast does it's type-safety check it will fail. You could try using static_cast rather than dynamic_cast, since static doesn't do a type-safety check, but really you shouldn't mix C and C++ allocation/casting styles like that.

tloach
+1  A: 

Rewrite your code so that you can read the type of the object in some way from your serialized archive. You can do this by string or by some custom values you use, but it probably won't be generic.

For example, if you are writing a CFoo object, first stream the value "1". If you are writing a CBar, stream the value "2 .

Then, when reading back the archive, if you see a "1" you know you have to "new" a CFoo, and if you read a "2" you know you have to new a CBar.

Alternatively, you could use a full-featured serialization library (or use it as inspiration). See for example boost::serialization

MadKeithV
+10  A: 

I have serialized a C++ object

I'm not sure you have. If you've written anything like this:

object *p = new objectchild();
some_file.write((char*)p, sizeof(objectchild));

then you haven't serialized your object. You've written some data to file, and (in most implementations) that data includes a pointer to a vtable and type information. When you "deserialize" the data, on another machine or in another run of the same program, the vtable will not in general be at the same address, and the pointer is useless.

The only way to serialize an object in C++ is to write its data members, in a known format you design. That known format should include enough information to work out the type of the object. There are frameworks that can help you with this, but unlike Java there is no mechanism built into the language or standard libraries.

Steve Jessop