The first call to operator* (live example line 38) is doing what is expected, it calls the overridden method operator_deref(). Whereas the second (live example line 40) is calling the parent method instead. What I'm missing here?
#include <iostream>
class RangeP{
protected:
int _iter = 0, _last;
virtual int operator_deref() const{
std::cout << "Parent Deref called" << std::endl;
return _iter;
}
public:
RangeP(int last_) : _last(last_) {}
// Iterable functions
const RangeP& begin() const { return *this; }
const RangeP& end() const { return *this; }
// Iterator functions
bool operator!=(const RangeP&) const { return _iter != _last; }
void operator++() { ++_iter; }
int operator*() {
return operator_deref();
}
};
class RangeC : public RangeP{
int operator_deref() const override{ // Enhanced operator
std::cout << "Child Deref called" << std::endl;
return 0;
}
public:
RangeC(int last_) : RangeP(last_) {};
};
int main(){
auto a = RangeC(1);
auto b = *a; // calls the overridden method as expected
for(auto i : RangeC(1)){} // calls the parent method (Why?)
}
/* Output *
Child Deref called
Parent Deref called
*/
Thank you very much in advance.