2

In Python, to compare types of variables, there is the function "type", for example: a = 10 and b = "abc", type (a)! = Type (b). Is there anything like it in C++? I have a vector of objects of the base class and I want to see if an element of that vector has been declared as derived class.

Makyen
  • 31,849
  • 12
  • 86
  • 121
  • There is probably a way to [check if an object is a subclass](https://stackoverflow.com/questions/307765/how-do-i-check-if-an-objects-type-is-a-particular-subclass-in-c) of another object. – Anderson Green Apr 23 '20 at 02:06
  • _I have a vector of objects of the base class_ If your vector is not store pointers you won't have any derived class objects in it? [Edit] the question to include code showing your declarations and how you're using it. – 1201ProgramAlarm Apr 23 '20 at 02:11
  • Does this answer your question? [typeid operator in C++](https://stackoverflow.com/questions/3721078/typeid-operator-in-c) – Ender_The_Xenocide Apr 23 '20 at 02:15
  • This is a duplicate and I have seen a question just like this but was unable to find the exact one. – Ender_The_Xenocide Apr 23 '20 at 02:16
  • @Ender_The_Xenocide is it [How do I get the type of a variable?](https://stackoverflow.com/questions/11310898/how-do-i-get-the-type-of-a-variable) ? – Louis Go Apr 23 '20 at 02:18
  • Yes, that is the one thank you @LouisGo – Ender_The_Xenocide Apr 23 '20 at 02:19

3 Answers3

5

Yup its called typeID

https://en.cppreference.com/w/cpp/language/typeid

if (typeid(a) == typeid(int()))
//code here
chrisHG
  • 80
  • 1
  • 2
  • 18
1

In C++, variables are statically typed.

bool eq_typed = std::is_same_v<std::decay_t<decltype(a)>, std::decay_t<decltype(b)>>;
bipll
  • 11,747
  • 1
  • 18
  • 32
0

Suppose you have a class D that inherits from class B, and an object of type D. But you only have a B* to that object for some reason.

Then dynamic_cast<D*>(object) evaluates to a D* that points to the same object. There is a run-time check to make sure that the conversion is safe; if you try to cast your object to a derived type it doesn't inherit from, you get back a null pointer instead.

You can also dynamic_cast references, if this fails a std::bad_cast exception is thrown.

If you want to do these types of runtime casts, what you really want is a std::vector<B*>, not a std::vector<B>. If you actually declare a std::vector<B> then none of them can ever be a D. But a B* can point to a plain-old B or any of B's derived types.

Jeff Linahan
  • 3,775
  • 5
  • 37
  • 56