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":
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:
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;
}
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.