Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to compare two downcasted object types in C++

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading