lundi 3 février 2020

Base constructor calls derived constructor depending on input - Choose object sub-type at runtime

Let's say I have a Human class:

class Human {
public:
    bool isFemale;
    double height;
    Human(bool isFemale, double height) {
        this->isFemale = isFemale;
        this->height = height;
    }
};

and derived classes, such as Female and Male, which implement their own methods. Do I have a way, in C++11, to determine at runtime, depending on the inputs into the Human constructor, which "sub-type" (Male or Female) Human should be? The ideal would be to always call the Human constructor, and the appropriate sub-type to be chosen at runtime, depending on the parameters one enters in the constructor. If that is possible, I guess one should twist the "Human" constructor, but I'm unsure how...

Aucun commentaire:

Enregistrer un commentaire