How can we Implement a c++ class such that it allows us to add data members at runtime
How can we Implement a c++ class suc开发者_开发技巧h that it allows us to add data members at runtime. This question was asked in an interview.
I find that to be a quite interesting interview question. If I was asking it, I would hope for that to be a starter of a back and forth conversation. The interviewed would have to know that you cannot add members dynamically, but I would hope for questions about the actual problem to solve (what do you want to solve? why do you need to add members?) and proposed solutions that would tackle those situations.
Note that there are two ways of looking to an interview question, looking for facts and looking for problem solving abilities. This is one question where both of them can be exercised (then again, it is up to the interviewer to lead the conversation, i.e. if the person just answers it's impossible, the interviewer can continue as but I need to be able to...)
You cannot do that in C++, there's not many languages you could do it in. You could have some sort of simulation of that with maps and such like but it's not the same thing.
I hope you just answered no.
Obviously you cannot change the class vtable at runtime - that's be silly, but you can use a single member variable that allows you to add entries to it, a stl map would be a good choice here.
As a map store name-value pairs, you would use it to store data comprising of the 'data member' name and the corresponding data value.
I hope you asked "what do you mean?" to that interview question and got them to explain just what they were thinking.
You cannot add data members in C++. You should look into containers for C++, perhaps the http://www.cplusplus.com/reference/stl/map/ which allows you to tag data with names.
精彩评论