0

I was wondering why to use inheritence, when you can easily come up with an alternative, which for me is more evident to use:

Let's say we have classes Parent, Child_1, and Child_2:

class Parent {
public:
    int x;
}

class Child_1 {
public:
    Parent p;
    string s;
}

class Child_2 {
public:
    Parent p;
    char c;
}

How is this different, than:

class Parent {
public:
    int x;
}

class Child_1 : public Parent {
public:
    string s;
}

class Child_2 : public Parent {
public:
    char c;
}

I understand that using inheritance allows us to use private, protected and public fields separately, but for me it complicates things more than being useful. To be honest, when I used private, it was more of a drawback, that I had to write getter and setter functions for private fields. Now I usually just put everything to public, for the sake of simplicity. Opinions?

Daniel
  • 391
  • 4
  • 17
  • 2
    you just rediscovered "composition over inheritance". Congratulations (no sarcasm!), thats the first step to realize that inheritance is not the solution to everything :) – 463035818_is_not_an_ai Apr 14 '20 at 11:47
  • Set this question aside in your mind, right now, and revisit it when you learn about virtual inheritance, and what it's used for. – Sam Varshavchik Apr 14 '20 at 11:47
  • Oh :D Well, thanks. That explains a lot. I didn't know how to search on the topic, but I suspected I wasn't the first who came across it. – Daniel Apr 14 '20 at 11:54
  • On some platforms in the example, the memory layout could very well be _identical_. For inheritance, the Child_1 and Child_2 _is-a_ Parent. But for the composition case, they are **not** an _is-a_ (polymorphic), they are a _has-a_ (composition). Which one to use? They both have their place, they're both useful, they both have caveats; use the right structure for the problem being solved. – Eljay Apr 14 '20 at 12:24

0 Answers0