-2

Classes in c++ can be extended, creating new classes which retain characteristics of the base class. This means we can create something like this :

struct Person
{
        struct Person** children;
        char[20] name;
        int age;
};

struct Teacher : public Person
{
       char[20] subject;
       int salary;
};

Does using this alternative make the code run slower than the inheritance version? :

struct Teacher
{
       struct Person personal_info;
       char[20] subject;
       int salary;
};

I personally prefer the second option, because I can clearly see which members come from struct Person when making variables from type struct Teacher and accessing those members. If struct Person has a field of another struct type, I can just typedef the access to that struct's fields and still see clearly what is going on. Does anything change performance wise? Do I have a good reason to use the first option over the second one?

4
  • 3
    Just to address your question about C++ - it's not possible to definitively or meaningfully answer that, you'd have to profile it yourself based on your particular implementation and your compiler. It seems extremely unlikely that you would find a real compiler or real world example where there would be any difference at all, but it's dependent on too many things to be usefully answerable on this site. Otherwise, inheritance and composition are structural design choices, generally guided by the kinds of considerations in the answer I've linked in my other comment. – Ben Cottrell Aug 14 '20 at 23:59
  • @Ben Cottrell Thank you, all of your comments are insightful. However it was the second one that truly answered my question – S.Sot Aug 15 '20 at 0:07
  • 2
    Does this answer your question? Why should I prefer composition over inheritance? – geocodezip Aug 15 '20 at 4:08
1

The main purpose of inheritance is differential code reuse. You don't see the advantages of that in your example, because your example literally has no code. It is not doing anything. If I were to run your example, absolutely nothing would happen.

Code reuse means just what you would think it does. It means not having to write code but instead reuse some existing code.

Differential code reuse refers to the situation where you have a variation of some existing concept, and instead of having to implement the entire concept, you only describe how that concept differs from the existing one.

For more on this concept, you might be interested in A Shared View of Sharing: The Treaty of Orlando by Lynn Andrea Stein, Henry Lieberman, David Ungar (1989), in particular the concept of Empathy described in that paper.

Not the answer you're looking for? Browse other questions tagged or ask your own question.