3

I have a C++ application which has the following classes:

  • class AAA
  • class BBB inherits from AAA
  • class CCC inherits from AAA
  • class DDD inherits from CCC

(All of the classes are marked as public)

Now I have the following map:

map <DWORD, AAA*> 

I find an AAA object in the map, by a DWORD id, but now I want to know what is the type of AAA:

this will be the logic:

if(AAA is BBB) { ... } if(AAA is CCC) { ... } if(AAA is DDD) { ... } 

Do you know how to write it in C++ (without adding a polymorphic function of getType())?

2
  • 1
    Why do you need to know the type? Commented Oct 27, 2011 at 9:27
  • 4
    Why is it required ? If your classes are polymorphic, the compiler would do the rest for you. Commented Oct 27, 2011 at 9:33

2 Answers 2

7

Requiring this indicates you are doing it the wrong way. You are trying to replicate something that virtual methods were invented for. Just put a virtual method in your base class.

class AAA { public: virtual void DoSomething() = 0; } class BBB : public AAA { public: void DoSomething() { ... } } class CCC : public AAA { public: void DoSomething() { ... } } class DDD : public AAA { public: void DoSomething() { ... } } 

And in your calling code, your logic is simple:

// no need for if() blocks. it's the point of virtual methods. AAA* somePointer; ... somePointer->DoSomething(); 

I realize you maybe can't just copy / paste your current "dosomething" code into this. But this is the pattern you should be using for this scenario. Perhaps instead of DoSomething it makes more sense to have something like GetSomeInfo, that the caller can use to do whatever it needs to do. The specific usage of this pattern depends on your context.

Sign up to request clarification or add additional context in comments.

Comments

4

If your object is polymorphic (i.e. has at least one virtual function), do a dynamic_cast<T*>.

if the result is not NULL then you have an object of type T. But a virtual function would be a better way to go IMO.

Note: RTTI will need to be enabled on your compiler (which it will be in the vast majority of situations)

EDIT: Thanks to @Als and @flipchart for additions

2 Comments

dynamic_cast works for only polymorphic classes. same goes for typeid(),which might give you erroneous results for non-polymorphic hierarchies.
dynamic_cast for pointers will return null. On references, it will throw an exception. Also note that this requires run time type identification (RTTI)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.