Search

11.1 — Introduction to inheritance

In the last chapter, we discussed object composition, where complex classes are constructed from simpler classes and types. Object composition is perfect for building new objects that have a “has-a” relationship with their parts. However, object composition is just one of the two major ways that C++ lets you construct complex classes. The second way is through inheritance, which models an “is-a” relationship between two objects.

Unlike object composition, which involves creating new objects by combining and connecting other objects, inheritance involves creating new objects by directly acquiring the attributes and behaviors of other objects and then extending or specializing them. Like object composition, inheritance is everywhere in real life. When you were conceived, you inherited your parents genes, and acquired physical attributes from both of them -- but then you added your own personality on top. Technological products (computers, cell phones, etc…) inherit features from their predecessors (often used for backwards compatibility). For example, the Intel Pentium processor inherited many of the features defined by the Intel 486 processor, which itself inherited features from earlier processors. C++ inherited many features from C, the language upon which it is based, and C inherited many of its features from the programming languages that came before it.

Consider apples and bananas. Although apples and bananas are different fruits, both have in common that they are fruits. And because apples and bananas are fruits, simple logic tells us that anything that is true of fruits is also true of apples and bananas. For example, all fruits have a name, a color, and a size. Therefore, apples and bananas also have a name, a color, and a size. We can say that apples and bananas inherit (acquire) these all of the properties of fruit because they are fruit. We also know that fruit undergoes a ripening process, by which it becomes edible. Because apples and bananas are fruit, we also know that apples and bananas will inherit the behavior of ripening.

Put into a diagram, the relationship between apples, bananas, and fruit might look something like this:

This diagram defines a hierarchy.

Hierarchies

A hierarchy is a diagram that shows how various objects are related. Most hierarchies either show a progression over time (386 -> 486 -> Pentium), or categorize things in a way that moves from general to specific (fruit -> apple -> red delicious). If you’ve ever taken biology, the famous domain, kingdom, phylum, class, order, family, genus, and species ordering defines a hierarchy (from general to specific).

Here’s another example of a hierarchy: a square is a rectangle, which is a quadrilateral, which is a shape. A right triangle is a triangle, which is also a shape. Put into a hierarchy diagram, that would look like this:

This diagram goes from general (top) to specific (bottom), with each item in the hierarchy inheriting the properties and behaviors of the item above it.

A look ahead

In this chapter, we’ll explore the basics of how inheritance works in C++.

Next chapter, we’ll explore how inheritance enables polymorphism (one of object-oriented programming’s big buzzwords) through virtual functions.

As we progress, we’ll also talk about inheritance’s key benefits, as well as some of the downsides.

11.2 -- Basic inheritance in C++
Index
10.x -- Chapter 10 comprehensive quiz

26 comments to 11.1 — Introduction to inheritance

  • Alper Ozge Gur

    The figure Rectangle<--Square caused a little shock on my side since this is the example used most frequently about how NOT to use inheritance. (I am coming from java and saw no clue if this is not the case with C++)

    No offence to authors is intended, these lessons are great (in terms of both depth of insight provided and yet not so hard to comprehend)by the way.

    • Alex

      It's the case for C++ as well. Do keep in mind that the goal of this lesson isn't to illustrate good form for programming inheritance, it's to appeal to the user's understanding of hierarchy in the world around us as a baseline for understanding how inheritance allows us to model hierarchies in programming.

      As a general note, it's hard to find examples that both show mechanics in a comprehensible way while simultaneously adhering to all best practices. In such cases, we'll typically favor comprehensibility for learning purposes, then return the best practices once we have the fundamentals and vocabulary to do so effectively.

  • Louis Cloete

    Just curious, does inheritance in the OOP sense allow for things like "a square is a rectangle and a rhombus, which are both parallelograms, which is a trapesium, which is a quadrilateral, which is a 2D geometric shape" ?

  • Dare

    if i have 4 classes i.e., A,B,C and D And i have to call class A into class D how can i do that?

  • ryder

    Hi, Alex or nascardriver, I encontour an issue that I still have no idea for a long
       time.
      
       In the following code snippet, I try to do a check that:

       ChildA is not inherient from ParentB.

       I want the program compile and print out me a message that tells me
       ~childA~ class is not inherient from ~ParentB~ ?

       They reason why I ask this question is that I am trying to
       understand a piece code in Unreal Game Editor.

       I will continue with my exploration but if you could add some reference to me. I would be really appreciate it. Thank you.

    • Output

      • ryder

        Thanks for pointing out this amazing std library: boost.

             It solve my problem.

             But, I recently have a temperation to know more details about
             c++. For example, after reading your code, I start to read source
             code of ~is_base_of_v~:

             I don't know if you are interesting to know how those code
             working? I mean, understanding to a degree such that a
             five-year-old girl could understanding if amount of time being
             post here.

             To be honest with you, I don't know how ~is_base_of_v~
             works. The things I can do is to google any things I don't
             understand.

             I am not sure it is very effective, but the key point is that I
             do not have any burdon on it. It's not like a semester that I
             have to finish it within some time. In my current case, I can
             study it as much as possible I'd like to.

        • > Thanks for pointing out this amazing std library: boost
          I did not and will not recommend using boost in my replies. boost is a feature-rich library of which many features have already been implemented into the standard library. You don't need boost. @std::is_base_of_v can be used after including the <type_traits> header.

          I don't think you read the chapter about templates yet, which is what this is all about. I'll try to keep it simple:
          I'm following the possible implementation shown at cppreference ( https://en.cppreference.com/w/cpp/types/is_base_of ). Actual implementations might differ.

          C++ has a feature, SFINAE. When the compiler has to construct types during compile time (Types that where not explicitly specified by the coder), an error might occur, because the type cannot be constructed (Don't confuse "construct" with constructors of classes, I mean "build" or "come up with"). This error isn't treated as a compiler error, instead the function/type it occurred at is ignored and cannot be used.
          @std::is_base_of first tests if both types are classes by attempting to create a pointer to a data member

          @T will be filled in by the compiler. If it can't be filled in, @T is not a class type.
          Once the compiler knows both types are classes, it checks if they are unions (I couldn't find an implementation for @std::is_union). If a type is a class and not a union, it continues.
          The compiler then tries creates a pointer to an object of the derived class and tries to call a function that has been overloaded to take either a pointer to the base class, or a void*. Base class pointer can implicitly be cast to parent class pointers. Depending on the function that has been called, the compiler knows if the type is a base of the other type.

          Once you're done with chapter 12, you can also use

          as opposed to the code I posted earlier. This should be easier to understand for now.

  • Cosmin

    Hello,

    I want to build a binary tree class and I'm trying to use a template so I can have different data-types binary trees. I have created first a Node class, it looks like this:

    And I'm trying to inherit the Node class to the binary tree, so I wrote something like this:

    When I want to create the definition of the BinaryTree constructor in a separate .cpp file, I receive the error: argument list for class template "BinaryTree" is missing. What it's wrong?

  • Omri

    By *atributes* in: "...Note that although children often redefine the attributes they inherit...", do you mean:
    a. member variables
    b. member functions
    c. both
    d. anything else?
    I think the term *redefinition* is new here and perhaps not fully clear.
    For variables, is it like reusing a name of a variable in a "contained" code block thus shadowing, within the block, its very existence outside the block?
    Have we ever redefined functions other than overloading them?

    • Alex

      Agree with your point of confusion. I've removed the term redefinition, and moved some of the C++ specific conversation into the next lesson.

      The basic idea is that if they wish, derived classes can override the value of member variables provided by the parent, or override the functionality of member functions provided by the parent. For functions, this is done via function overloading.

  • Alexander

    Wow, it's been 8 years, 9 months and 24 days; and nobody pointed out the zuchinni (should be "zucchini" ofc) being misspelled?! :o Well then, let me be -that- guy. :D

  • Sylvio

    This material is just amazing. My greatful thanks to the author!

  • BHIKSHAPATHI

    why inheritance?without inheritance cant i do what exactly inheritance does.

    • Alex

      Once you've read through the rest of this chapter and next, and I think you'll see that inheritance gives you a lot of useful tools to do things that would be difficult or extremely redundant to do otherwise. Inheritance, properly used, can save you massive amounts of time and make your code significantly easier to maintain (by reducing the amount of redundant code you have to write and test).

  • prabodh

    Intro. abt inheritance is good

    but i have lots of confusion in inheritance like public,private and protected decleration (in inheritance)....please give me the simple trick so that i can understand very easily.........

Leave a Comment

Put all code inside code tags: [code]your code here[/code]