I want to compare two objects that are derived from the same base type but are not the same derived class. So I made the == operator virtual and over-ride it in derived classes.
When I store all of my objects in an array of the base type, the derived implementation is not called, it goes straight to the base implementation. It does however work when the array is of type pointer to base class, and a de-reference the elements.
Could some-one please explain why this behaviour occurs? It baffles me ;-)
enum eType {
BASE_TYPE,
DERIVED_TYPE
};
class A {
eType mType;
public:
A() : mType(BASE_TYPE) {}
A(eType Type) : mType(Type) {}
virtual bool operator == (A &Other) {
return mType == Other.mType;
}
};
class B : public A {
int bVal;
public:
B(int Val) : A(DERIVED_TYPE), bVal(Val) {}
virtual bool operator == (A &Other) {
if(!(A::operator ==(Other))) {
return false;
}
B* myB = (B*)&Other;
return bVal == myB->bVal;
}
};
int main(int argc, char *argv[])
{
A a1, a2;
B b1(0);
B b2(1);
bool result = false;
// Calls implementation in A
result = (a1 == a2);
// Calls implementation in B
result = (b1 == b2);
A aArray[2];
aArray[0] = b1;
aArray[1] = b2;
// Calls implementation in A!
result = (aArray[0] == aArray[1]);
A *aRefArray[2];
aRefArray[0] = &b1;
aRefArray[1] = &b2;
// Calls implementation in B
result = ((*aRefArray[0]) == (*aRefArray[1]));
return 0;
}