user1703993
user1703993

Reputation: 61

How can I check an object's class in C++?

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.

Upvotes: 1

Views: 171

Answers (3)

Borg8
Borg8

Reputation: 1662

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";
    }
}

Upvotes: 0

peoro
peoro

Reputation: 26060

If your base class has some virtual members (i.e. it's polymorphic, as I think it should be in a case like this one) you could try to down cast each member to find out its type (i.e. using dynamic_cast).

Otherwise you could use RTTI (i.e. typeid).

Upvotes: 2

user1708860
user1708860

Reputation: 1753

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.

Upvotes: 0

Related Questions