I have got two std::vector
s of pointers to classes A
and B
and am trying to make a method that removes an object from those vectors. This Object may or may not be a subclass of A
and/or B
and does not have to be an Element of any of the vectors. I have tried following code:
void removeObject(void *object) {
A *pa = static_cast<A*>(object);
std::vector<A*>::iterator aPos = std::find(as.begin(), as.end(), pa);
if (aPos != as.end())
as.erase(aPos);
B *pb = static_cast<B*>(object);
std::vector<B*>::iterator bPos = std::find(bs.begin(), bs.end(), pb);
if (bPos != bs.end())
bs.erase(bPos);
}
but the pointers have different values, so std::find
doesn't work (or rather it works sometimes). After reading Multiple inheritance pointer comparison and C++ pointer multi-inheritance fun I understand why, but in both cases the suggested solution was to cast the pointer to *subclass
. My questions are:
- How can I check whether two pointers refer to the same object without knowing its type?
- Is there a more elegant solution to my problem?
I am new to C++ so please excuse me if I have thoroughly misunderstood something...