Std :: find for inheriting a C ++ object

1. So, I:

Class A; Class B : public A; Class C : public B; 

2. And a vector of type B pointers:

 vector<B*> vec; 

3.Then:

 C* ptr = new C(); vec.push_back(ptr); 

So the question is, is it possible to use std :: find like this?

 std::find(vec.begin(), vec.end(), prt); 

Also, is it good to do a search using this-> pointer?

 std::find(vec.begin(), vec.end(), this); //inside of a type C object 

Thanks in advance.

+4
source share
1 answer

Yes, this is safe, as there is a clear comparison ( == ) between pointers to objects in the type hierarchy. Despite the fact that the actual value of the pointers may differ after conversion to the type of the base class (often in the case of multiple inheritance), the runtime must be adjusted for this, so that comparisons between these pointers still lead to the correct result.

+4
source

All Articles