There is an abstract class Human , two classes are inherited from it: Man and Woman . I create an instance, but I do not know whether it is a man or a woman.

How competently is this problem solved in practice?

At the moment it is written as follows, but it’s not done like that ...

 class Human {}; class Man : public Human {}; class Woman : public Human {}; Human *createHuman(bool gender); // Возвращает указатель на созданный Man или Woman int main() { Human *firstHuman = createHuman(1); } 

Is this problem solved through the Human class constructor?

  • What is the actual problem? What exactly does not suit you in the code? (I would encode the floor not by a number, but by enum.) - VladD
  • @VladD I assumed that it was possible to somehow implement this not through a separate function, but through the constructor of the Human class. Human * firstHuman = new Human (1); A pointer will come to the class of Man or Woman - artyomdevyatov
  • 2
    Through the constructor of the class Human there is no way: only Human can return from it. Do through the factory method createHuman . - VladD
  • @artyomdevyatov: The constructor is called after the "raw" memory for the object is already allocated. Therefore, it is obvious that in the constructor it is already too late to decide whether it will be Man or Woman , because in general, the sizes of these types may be different. The decision that you will create must be made before the memory is allocated. - AnT

1 answer 1

Transferred from comment:

Through the constructor of the class Human it is impossible to do the necessary: ​​the Human type can return from the Human constructor. What you use is the factory method, the common way to solve your problem. So you do it right.


I would just replace bool gender with enum , since true does not have an obvious binding to any of the sexes.