Suppose I have a vector of objects of a base class, but use it to contain a number of derived classes. I want to check whether or not a member of that vector is of a specific class. How do I do that? I can think of making a template of a derived class that takes in a parameter of the base class, but I am not sure how I can compare the class with the object.
-
Here is a possible place to start: stackoverflow.com/questions/351845/…MikeB– MikeB2012-10-01 16:57:16 +00:00Commented Oct 1, 2012 at 16:57
-
5If you have a vector of objects of a base class you don't have any objects of derived types; they got sliced when they were stored in the vector.Pete Becker– Pete Becker2012-10-01 16:59:06 +00:00Commented Oct 1, 2012 at 16:59
-
1The real question is why do you need to know the type at all. More often than not it is a design flaw.Zdeslav Vojkovic– Zdeslav Vojkovic2012-10-01 16:59:43 +00:00Commented Oct 1, 2012 at 16:59
-
1You're misunderstanding what you're doing. A vector is a homogeneous array of elements of the same type. Either you've sliced your objects into base objects, or you have a vector of pointers. In any event, your design is probably misguided.Kerrek SB– Kerrek SB2012-10-01 17:00:43 +00:00Commented Oct 1, 2012 at 17:00
-
@PeteBecker good point. I totally missed that 'detail'Zdeslav Vojkovic– Zdeslav Vojkovic2012-10-01 17:00:58 +00:00Commented Oct 1, 2012 at 17:00
|
Show 2 more comments
3 Answers
You can use the dynamic_cast
But if you need to do that, then you probably have a design problem. you should use polymorphism or templates to solve this problem.
Comments
check out this example:
#include <iostream>
using namespace std;
#include <typeinfo>
class A
{
public:
virtual ~A()
{
}
};
class B : public A
{
public:
virtual ~B()
{
}
};
void main()
{
A *a = new A();
B *b = new B();
if (typeid(a) == typeid(b))
{
cout << "a type equals to b type\n";
}
else
{
cout << "a type is not equals to b type\n";
}
if (dynamic_cast<A *>(b) != NULL)
{
cout << "b is instance of A\n";
}
else
{
cout << "b is not instance of A\n";
}
if (dynamic_cast<B *>(a) != NULL)
{
cout << "a is instance of B\n";
}
else
{
cout << "a is not instance of B\n";
}
a = new B();
if (typeid(a) == typeid(b))
{
cout << "a type equals to b type\n";
}
else
{
cout << "a type is not equals to b type\n";
}
if (dynamic_cast<B *>(a) != NULL)
{
cout << "a is instance of B\n";
}
else
{
cout << "a is not instance of B\n";
}
}