Hi people. I just had a problem. I want to know how to take name of class as an argument. I think i can do it by using a string variable within the class.
For eg. I hava a class "Ion" and "Calcium" is an instance of class Ion.What i want to do is when a user inputs Calcium, i want to retrieve Calcium from a list of Ion objects and then process it. Is this possible to do it without assigning a string variable "name" in the declaration of Ion.
Your instinct is correct - you've got to store the name as a member. Then just check each class name against the user input until they match, and do what you need from there. C++ doesn't have a built-in way for you do this.
MFC uses macros which sort of "simulate" this effect, but similarly, they just force the compiler to insert a few lines of code in the class behind the scenes, using a static class (which contains the class name, and a few other things) and a "get" method.
The problem with that method is that the string name() returns can vary from compiler to compiler. GCC preprends the length of the class name as seen above, so you can give your ion class a name() function that calls typeid on itself and strips that number. While that method works, it's not fully portable.