Use Name of Class as Input command

Jun 1, 2010 at 8:40am
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.
Jun 1, 2010 at 10:51am
You can use a dictionary as container (list of objects). You can not find classes by the name you give them in your code.
Jun 2, 2010 at 10:12am
Thanks although that didnt help much.
Jun 2, 2010 at 4:35pm
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.
Last edited on Jun 2, 2010 at 4:50pm
Jun 2, 2010 at 5:29pm
One should mention that there is typeid. You can get the type of any polymorphic object that way.

1
2
Ion* ion=new Calcium();
cout << typeid(*ion).name() << endl;

prints:
7Calcium

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.
Jun 3, 2010 at 10:15am
Thanks i'll try :)

EDIT : Calcium is not an object it is just an instance of an object. When i try it, the output is
Class Ion


1
2
class Ion{
} Calcium;
Last edited on Jun 3, 2010 at 10:41am
Topic archived. No new replies allowed.