How to find out the parent class?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Animal  {};

class Mammals : public Animal {};
class Birds : public Animal {};
class Aquatic : public Animal {};

class Fox: public Mammals {};
class Cat: public Mammals {};

class Hawk: public Birds {};
class Duck: public Birds {};

class Fish: public Aquatic {};
class Crab: public Aquatic {};


How do I know if a class is an immediate subclass or a distance subclass of another? For example,

Hawk hawk;

how do I check that "hawk" is a bird?

What if Hawk becomes the parent to other classes? For example,

class RedTailedHawk : public Hawk {};

RedTailedHawk rtHawk;

how do I check that "rtHawk" is a bird?
how do I check that "rtHawk" is a bird?

http://en.cppreference.com/w/cpp/types/is_base_of

Last edited on
I tried

1
2
Hawk hawk;
    std::cout << "Birds2Hawk: " << std::is_base_of<Birds, hawk>::value << '\n';


and got the following errors:

error: the value of 'hawk' is not usable in a constant expression
std::cout << "Birds2Hawk: " << std::is_base_of<Birds, hawk>::value << '\n';
^


error: type/value mismatch at argument 2 in template parameter list for 'template<class, class> struct std::is_base_of'
std::cout << "Birds2Hawk: " << std::is_base_of<Birds, hawk>::value << '\n';
^
closed account (E0p9LyTq)
Isn't your class Hawk instead of hawk?
Correct but I'm not trying to check the class. I want to know if the instance hawk, Hawk hawk;, is of type Mammals, Birds or Aquatic?
closed account (E0p9LyTq)
Look at dynamic_cast for run-time type information.

http://en.cppreference.com/w/cpp/language/dynamic_cast
Use the fuller signature of is_base_of:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <type_traits>

class Animal  {};
class Birds : public Animal {};
class Hawk: public Birds {};
class RedTailedHawk : public Hawk {};

int main()
{
    std::cout << std::boolalpha;
    std::cout << std::is_base_of<Birds, RedTailedHawk>::value << '\n'; // true
}
edit: also works for private inheritance
Last edited on
Correct but I'm not trying to check the class. I want to know if the instance hawk, Hawk hawk;, is of type Mammals, Birds or Aquatic?
1
2
3
4
5
6
template <typename Base>
using is_base_of_hawk = std::is_base_of<Base, decltype(hawk)>;
bool constexpr result = 
  is_base_of_hawk<Birds>::value ||
  is_base_of_hawk<Mammals>::value ||
  is_base_of_hawk<Aquatic>::value; 

If you would rather query which of the three classes is a base of Hawk, you can do that statically in a similar way.

If the type of hawk is dynamic, then you need RTTI. But that wasn't specified in the question.
Topic archived. No new replies allowed.