1

Simplifed example of my problem :

I have an abstract class A. I have two abstract classes B and C inheriting from A. And I have a lot of final classes inheriting from B or C :

class A;
class B : public A;
class C : public A;
class B1 : public B;
class B2 : public B;
class C1 : public C;
class C2 : public C;

I implement an algorithm recieving a pointer of A having to know if the type comes from B or C to work properly :

void algorithm(boost::shared_ptr<const A> a)
{
  if(*a is a B instance)
    // do something
  else if(*a is a C instance)
    // do something other
}

How can I check that simply without C++11 ?

I know how to check the final type with typeid(*a) == typeid(C1), but I don't know how to check a parent type...

Caduchon
  • 4,574
  • 4
  • 26
  • 67

2 Answers2

2

You can use dynamic_pointer_cast:

if (std::dynamic_pointer_cast<B>(a)) {
   ...
}
else if (std::dynamic_pointer_cast<C>(a) {
   ...
}
Ivan Mushketyk
  • 8,107
  • 7
  • 50
  • 67
  • Hum... This is C++11, but it's also defined in boost. It seems so simple ! Is it also a good way to test the final type ? Or the check with `typeid` is better ? – Caduchon Jun 29 '15 at 08:59
  • If you want to know exact type, use typeid. But to comply to Liskov substitution principle it's better to use dynamic cast. Since instances of B1and B2 should work just as B so it should not matter if it instance of B or if it one of subclasses. – Ivan Mushketyk Jun 29 '15 at 09:29
2

Use dynamic_cast.

 if (dynamic_cast<B *>(a))
 {
      //   // a actually points at a B, or something derived unambiguously from B
 }

Of course, more generally, you need to revisit the design of your function. More often than not, it would be better that it not need to know about classes derived from A. Avoiding that usually means using A as a polymorphic base that provides an interface to all functionality needed in the function (e.g. set of virtual functions that classes like B and C might specialise for themselves).

Peter
  • 35,646
  • 4
  • 32
  • 74
  • You're right. But actually it's for a dump/load process having to know the real type of the object in order to be able to reallocate it with the exact type. – Caduchon Jun 29 '15 at 09:15