Archived

This topic is now archived and is closed to further replies.

How to determine a class type

This topic is 5816 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites