limi
limi

Reputation: 848

How to know whether two objects are derived from same base class?

For example:

class Base{...};

class Sub1 : public Base{...};

class Sub2 : public Base{...};

Sub1 s1;
Sub2 s2;

bool is_same_base(void *obj1, void *obj2){
...
}

if(is_same_base(s1,s2){
     printf("Great! S1 and S2 and from same base class!\n");
}

In this case, I am not sure what's the best/fast way to know if the obj1 and obj2 are derived same base class?

One possible but slowest way is to compare the virtual table entries one by one, if any function pointer exists at both virtual tables, then I can say they are derived from same base class. This is not efficient.

Any comment?

Upvotes: 1

Views: 181

Answers (1)

Carl
Carl

Reputation: 44458

You have to know the base class. You can't use dynamic cast without knowing what type to dynamic cast to. There is also typeid, but again, that does not give you the base class.

Here's the way I see it:

  1. In order to use an instance of Sub1 and Sub2, you need to include "Sub1.h" and "Sub2.h" (assuming they're not declared in the same file).
  2. Sub1.h and Sub2.h need to mention which base class Sub1 and Sub2 inherit from, or the code will not compile.

In other words, there is no way you can be prevented from simply looking up the common base class yourself, so I don't see why you would need to do this in the first place.

Edit: You can't use void pointers, because then you're throwing away the type information anyway. The only way you could do this kind of thing is probably at compile time, using Template metaprogramming (I could be wrong), but then your classes need to be written with this kind of use in mind. From what I can tell, it looks like modifying the original class code is not an option.

Upvotes: 3

Related Questions