I have two structs, in which I’m trying to overwrite a method in the base struct.
The base struct is defined as:
template <class T>
struct compareFunction : public std::binary_function<T,T,bool> {
virtual bool operator() (const T & first, const T & second) {
//This function is always called
return first < second;
}
};
The struct I’m attempting to subclass with is defined as:
template <class Key, class T>
struct valuecomparer : public compareFunction<std::pair<Key,T> > {
std::binary_function<Key, Key,bool> comparer;
bool operator() (const std::pair<Key, T>& x, const std::pair<Key, T> & y) {
//This function is never called
Key tx = x.first;
Key ty = y.first;
if(tx < ty) {
return true;
} else {
return false;
}
}
};
I don’t see what I’m doing wrong here, any help would be greatly appreciated.
Ideally, the method in valuecomparer would be called instead of the method in compareFunction.
It is being called basically like this (not necessarily valid syntax,but trying to get idea across):
typedef compareFunction<T> cmpType; //Inside a class definition, T is std::pair<int,double>
valuecomparer<int,double> compareVar;
compareVar.comparer = std:less<int>();
cmpType x = compareVar;
x.compare(std::pair<int,double>(8,20.0),std::pair<int,double>(8,25.0));
Apparently after switching the storage from a pure struct to a struct pointer in the class that is using the base struct (and consequently derived struct), everything works. Thanks for all the help 🙂
According to the code you’ve posted, in order to have a overridden derived class’ function to be called, you MUST call it from a pointer or reference to the base class type, not an object whose type is of the base class itself. So when you create code like this:
that’s always going to call the function definition in the base-class since there is no function that can be used for the polymorphic derived function call. The copy-constructor only copies over the v-table entries and associated members from the base-class. So when you call a method on an object of the base-class type, even if you’ve created that object from a copy of a derived class, you still end up with the base-class method calls. You would have to-do something like this:
Now when the
operator()method is called onx, the correct v-table entry is used, that is the overridden version ofoperator()inside ofvaluecomparer.