How to determine a class type

Started by
4 comments, last by NewDeal 22 years, 3 months ago
Scenario: I have a base class A which several other classes (B and C) are inherited from. Instances of classes B and C are created dynamically. Everytime a class is created it is added to a running list with objects of type A (and thereby B and C). What i need is a way to determine if a class is of type B or C during runtime. At this moment i''ve included a variable in the parent class containing af unique identifier for each child class. I know there''s a better solution but i cant seem to figure it out. Any help would be very appreciated. Thanks in advance
Advertisement
The short answer is - the typeid() operator

MyClass x;

typeid(x) - returns typeinfo


The longer answer is - why does the other code care which derived class type it is?

This is usually better handled by polymorphism - eg more virtual functions and/or abstract classes

without knowing exactly what you are doing its hard to say if using the typeid operator is really the best answer.
Now you asked for it (well you didnt but i need the help)

Im working on a parser for mathematical expressions. I can parse the textual representations fine and build up an expression tree.
The tree consists of the classes given below.

  class ExpTree{public:	ExpTree *LeftChild;	ExpTree *RightChild;	int tempType;public:	ExpTree();};class ExpNumeric : public ExpTree{	float Value;public:	ExpNumeric(float newValue);	float getValue();};class ExpSymbolic : public ExpTree{	char Symbol[64];public:	ExpSymbolic(char *newSymbol);	char *getSymbol();};class ExpOperator : public ExpTree{public:	short int Type;public:	ExpOperator(short int newType);	short int getType();};  


The problem arises when i need to print the expression. This has to be done using the tree. I traverse the tree, but at leaf nodes where the variables or numeric values exist, i need to know whether im dealing with one or another.

I you can change the implementation of the classes change them to be abstract classes, otherwise on the contructor turn you pointer to the childs to 0, if a node has both childs 0 after the parsing then it is a leaf
humanity will always be slaved by its ignorance
..then there should be a virtual "Print" function, and you don''t need to know the type. SteveC hit the nail on the head.
Nevermind, figured it out.
Polymorphism was what i needed ofcourse. I have been trying to get it working for the last hour with out any luck. Just found out where i was going wrong and now everything works as a charm.

This topic is closed to new replies.

Advertisement