Home > OS >  How to compare two downcasted object types in C
How to compare two downcasted object types in C

Time:07-28

I have two objects inheriting from Base class. Both are stored in vector:

std::vector<Base*> m_vector;

How can I check if the first type of object is equal to the second type of object?

Scenarios:

1.

  • First object type: A : public Base
  • Second object type: B : public Base
  • Result: Not equal
  • First object type: A : public Base
  • Second object type: A : public Base
  • Result: Equal
  • First object type: A : public Base
  • Second object type: B : public A
  • Result: Not equal

CodePudding user response:

I am simplifying things a lot to get a point across. You have a

std::vector<Base*> m_vector;

This basically means: You have a vector of pointers to B. The actual objects are polymorphic, meaning you don't care what the actual type is as long as they inherit from B.

Now you want to do something that requires you to know the actual type of the elements.

Thats a contradiction.

The easiest way to solve that contradiction is to give up the second point: Don't care what the actual type is, use only the interface defined in the base class.

One way to do that is to use typeid. For example:

#include <iostream>
#include <typeinfo>
#include <memory>
#include <vector>

struct Base {
    bool same_type(const Base& other) {
        return typeid(*this) == typeid(other);
    }
    virtual ~Base() = default;
};

struct A : Base {};
struct B : Base {};

int main() {
    std::vector<std::unique_ptr<Base>> x;
    x.emplace_back(std::make_unique<A>());
    x.emplace_back(std::make_unique<B>());
    x.emplace_back(std::make_unique<B>());
    
    std::cout << "expect 0 : " << (x[0]->same_type(*x[1])) << "\n";
    std::cout << "expect 1 : " << (x[1]->same_type(*x[2])) << "\n";
}

For details on typeid I refer you to https://en.cppreference.com/w/cpp/language/typeid.

As suggested in a comment, you don't actually need to write a Base::same_type() but you can use typeid directly.

  •  Tags:  
  • c
  • Related