0
votes

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
1
are there only two derived classes or more? How is 1 different from 3 ? - 463035818_is_not_a_number
You could give the base type a pure virtual "type()" function that all derived classes must implement. Then compare based on what type() returns.. - Jesper Juhl
You can't have class B: public Base {}; and class B: public A {}; at the same time. - pptaszni
Just to be clear, you want to compare the types of the objects, not the objects themselves? If so then that would simply be typeid(*a) == typeid(*b) assuming your types are polymorphic. - john
If you don't want to write additional "compare" or "type" methods, you can just use en.cppreference.com/w/cpp/language/typeid and compare name or index of your types (for it to work, then need to be polymorphic). - pptaszni

1 Answers

1
votes

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.