equivalent to the Java class Object

Hello!

I am translating one of my Java classes into C++. This class is a FileHandler that writes and reads objects to files. In Java it is possible to manage input and output of objects using the abstract Class "Object":

1
2
3
4
5
6
static void writeObjectFile(Object obj, string url) {

}
static Object readObject(string url){
    return NULL;
}


In C++ this does not compile. How do you solve problems like this in C++?

when on the topic, is there a C++ equivalent to ArrayList<Object> ?

Thanks in advance!
I recommend forgetting Java and start learning C++ from scratch.

There is no equivalent of class Object in C++, there is no native object serialization.

Generics in C++ is implemented as templates which are not the same but provide some similar functionality.

One 'equivalent' of an ArrayList<MyType> could be std::vector<MyType>.
I recommend forgetting Java and start learning C++ from scratch.

Ok!

Then how do I write a function that can use all sorts of objects as input/output? Is it possible to notify the method of what Class it is supposed to use when saving objects? For example:

void saveObjectFile(url, objectName, className ){} ?
Last edited on
There is no simple way to automajically serialise an object the way Java does, because Java runs in a highly 'managed' environment. C++ runs directly on the CPU.

Each class (or subclass) will need to manage its own input/output. There are some libraries that seek to make this task easier though.

Typically in C++ you will write an input operator and an output operator for each class you want to serialize/deserialize:

1
2
3
4
5
6
7
8
9
10
11
class MyType
{
    friend std::ostream& operator<<(std::ostream& os, const MyType& m);
    // .. class decl..
};

std::ostream& operator<<(std::ostream& os, const MyType& m)
{
    // code to serialize MyType goes here....
    return os;
}
What about using templates?

Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type.

http://www.cplusplus.com/doc/tutorial/templates/
Each class still needs to know how to serialise itself.
Boost provides a serialization library: http://www.boost.org/doc/libs/1_43_0/libs/serialization/doc/index.html
BTW, why are all your function static?
Topic archived. No new replies allowed.