Could somebody help me understand what is going wrong with this type heirachy for validating input. Basically I have a superclass which can accept any string argument and a set of subclasses which can only accept certain inputs. I want to use inheritance to build an elegant way to check user input without duplicating code. Here is an example that has a few problems:
class Word {
std::string word_;
public:
Word(const std::string &word) {
word_ = word;
validateWord();
}
virtual std::vector<std::string> getValidWords(){
return std::vector<std::string>({"All"});
}
void validateWord(){
std::vector<std::string> valid_words = getValidWords();
if (valid_words.size() == 1) {
if (std::find(valid_words.begin(), valid_words.end(), "All") != valid_words.end()) {
return;
}
}
if (std::find(valid_words.begin(), valid_words.end(), word_) == valid_words.end()){
throw std::invalid_argument("Word \"" + word_ + "\" not in valid words" );
}
}
};
class OneToThree : public Word {
public:
explicit OneToThree(std::string word) : Word(word) {
};
std::vector<std::string> getValidWords() override {
return std::vector<std::string>( {"One", "Two", "Three"});
}
};
int main() {
OneToThree var1("Three"); // should be fine
OneToThree var2("randomWord"); // should fail
};
The debugger is telling me that the getValidWords()
method from the subclasses are not being used in the validation function, but the one from the superclass.
Could anybody suggest the right way to do this?