SomeGuy SomeGuy - 1 year ago 90
C++ Question

Initialising class through a parser

I have a class which I'll name CObject with a lot of private data members..

class CObject
int a, b, c, d, e, f, g, h, i;
string j;
...More data types etc

And another class which parses an initialisation file recursively finding members of objects.. This class is satisfying a virtual class provided by a library.

class CParser
void beginParsingObject()

void parseObjectMembers(string name, int a)
//Found a member variable of the object!

void finishParsingObject()
//Finish up parsing the object

So "parseObjectMembers" would be called as many times as there are member variables in the CObject class.

The CObject class will have it's member variables populated when the parser finds it's next member variable in the entry of it's data files.

Here is my quandary:

What would be a good way to set the member variables in CObject as the data is read?

-Using a constructor would mean caching every value that comes through, and constructing the object on completion of parsing the object - less than satisfactory as there's a lot, and I want the parser to be pretty generic.

-Using getters and setters in the CObject class would expose all the member variables to everything else, where that's not needed or wanted.

-Using an initialise function would be fine, but I don't want anything else having access to that function - a friend function maybe?

Any ideas are appreciated, and I'll clarify where I can. Sorry the code is obscure and not very fleshed out, but hopefully it's enough to see the crux of the problem.


Answer Source

What you describe seems to be serialization / deserialization. It is very common to backup / retrieve objects data from (XML) configuration file. Maybe a good start is Boost Serialization Tutorial.

More basically the answer to your question could be "use a 'friend' function / class of the class itself".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download