#include <cstdio>
#include <exception>
usingnamespace std;
class TimeException: public exception {
public:
virtualconstchar* what() constthrow() {
return"Wrong Time Format";
}
};
class HourException: public TimeException {
public:
constchar* what() constthrow() {
return"Hour must lies between 0 and 23";
}
};
struct Hour {
Hour(int h) {
if (h < 0 || h >= 24) {
throw HourException();
}
val = h;
}
int getHour() { return val; }
int val;
};
int main() {
try {
Hour h(-5);
printf("%d\n", h.getHour());
}
catch (TimeException e) {
printf("%s\n", e.what());
}
}
To my belief, when TimeException is being caught during execution, the what function being called will be the HourFunction one because of the presence of virtual keyword in TimeException.
When I try to execute it however, the result is "Wrong Time Format" instead: what function in TimeException is being called instead.
Can anyone let me know what I have coded wrong that has led to such behavior?