-2

I have this structure:

class IIterator : public ICollectible{};
class A: public ICollectible{};
class b: public A{};
class c: public A{};
class d: public A{};

When I do something like this

IIterator* it = colection->getIterator();
whatType* db = dynamic_cast<whatType*>(it->hasCurrent());

colection is list with elements of type A (it could have objects of type b, c or d) hasCurrent() gives me something type ICollectible, so I have to do

dynamic cast so I can work with b, c or d, but how do I know which one it is?

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141

1 Answers1

2

The point of dynamic_cast is that it tells you if you have the right type, or it returns nullptr. So you can do:

if (b *p = dynamic_cast<b *>(it->hasCurrent())) {
    // its b
} else if (c *p = dynamic_cast<c *>(it->hasCurrent())) {
    // its c
} else if (d *p = dynamic_cast<d *>(it->hasCurrent())) {
    // its d
} else {
    // none of the above

Of course, many OO purists will consider this a "bad code smell" -- you should define a virtual function in your interface class and call that, rather than testing for different derived types.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226