Writing code in C++ is not a trivial task, but quite manageable for anyone who gets into his or her head the desire to achieve success in the coding segment of life. To make the coding process more understandable, C++ offers the stream concept. This article will be all about how to make your class compatible with this technology.
Serialize Your Class into Streams in C++ - The Insertion (Page 3 of 4 )
The insertion operation is completed by the >> operator. It is a smart move from the designing team to overload the bitwise shift operator for types where you cannot do this, indeed where this does not make any sense. Reusability is once again scheduled.
The first task we need to do is define the function of the operator overload like this:
This is overloading the operator << (in fact it defines the operator) for types where, on the left side of the operator is an ostream, and on the right side a car type. The const assures the input class that through this process the data of the "per" will not change, and the reference passing of the argument is for performance purposes, as we avoid creating a new object and copying the data from the input inside it.
Now all we need to do is perform the insertion of the class inside the function into the ostream. Nevertheless, here we have a small design issue. We need to access all of the data in the "car" class inside the function, as we might or might not have functions that guarantee access to its private or protected members.
Here for instance we have the getName() and getID() public methods for this, but designing a class that will not divulge a member that we still want to serialize is surely an achievable task. Besides calling, a function can decrease the performance of your program. We need to make sure that we have access to all of the members of the class, so the road we need to pass on is the friend keyword.
Applying the upper declaration of the function inside the car class will point out to the compiler that this function is a friend with the class and guarantee access to all non-public members/functions, just as if those were public. Now we can define the function outside the class in the following manner:
Inside the function, we just pass each build in type C into the stream, and you might want to make sure that the members are separated by some white spaces (or else you will see a long sequence of chars in your streams). Also make sure to call a flush at the end of your streaming (here the endl has encapsulated that option); otherwise, they might just be pushed into the buffer and, in the end, not displayed properly.