Parent and Child Classes

Hello. I have a base class and multiple derived classes that completely serve different purposes and would like to know if there is a way to store a child class object in the Parent class, or if I should take a different approach.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  class Parent{
    //Store child class 1, 2, or 3, objects here.
  };

  class Child_1 : public Parent{
    string text;
  };

  class Child_2 : public Parent{
    bool hasTest;
    string question;
  };

  class Child_3 : public Parent{
    int chance;
  };


I have a 2 dimensional array storing Parent classes, and am hoping that I can use that class to obtain one of the three child classes.
Last edited on
Inheritance should be used to model an is-a relationship: each sub-class is its super-class. If each class provides a uniform interface, than you can use dynamic dispatch (i.e., runtime polymorphism) or RTTI to extract the right behavior or the right object.

In the case where your sub-classes serve entirely different purposes, you don't need inheritance but rather a discriminated union.
Consider std::any or std::variant, with a preference towards the latter. If those aren't available, you can use the boost alternatives or write it yourself.
Last edited on
… would like to know if there is a way to store a child class object in the Parent class
the truly polymorphic way would be via base class pointers but as max points out, the case for inheritance in your particular case seems weak
http://stackoverflow.com/questions/9425822/why-use-base-class-pointers-for-derived-classes
Topic archived. No new replies allowed.