Search

11.3 — Order of construction of derived classes

In the previous lesson on basic inheritance in C++, you learned that classes can inherit members and functions from other classes. In this lesson, we’re going to take a closer look at the order of construction that happens when a derived class is instantiated.

First, let’s introduce some new classes that will help us illustrate some important points.

In this example, class Derived is derived from class Base.

Because Derived inherits functions and variables from Base, you may assume that the members of Base are copied into Derived. However, this is not true. Instead, we can consider Derived as a two part class: one part Derived, and one part Base.

You’ve already seen plenty examples of what happens when we instantiate a normal (non-derived) class:

Base is a non-derived class because it does not inherit from any other classes. C++ allocates memory for Base, then calls Base’s default constructor to do the initialization.

Now let’s take a look at what happens when we instantiate a derived class:

If you were to try this yourself, you wouldn’t notice any difference from the previous example where we instantiate non-derived class Base. But behind the scenes, things happen slightly different. As mentioned above, Derived is really two parts: a Base part, and a Derived part. When C++ constructs derived objects, it does so in phases. First, the most-base class (at the top of the inheritance tree) is constructed first. Then each child class is constructed in order, until the most-child class (at the bottom of the inheritance tree) is constructed last.

So when we instantiate an instance of Derived, first the Base portion of Derived is constructed (using the Base default constructor). Once the Base portion is finished, the Derived portion is constructed (using the Derived default constructor). At this point, there are no more derived classes, so we are done.

This process is actually easy to illustrate.

This program produces the following result:

Instantiating Base
Base
Instantiating Derived
Base
Derived

As you can see, when we constructed Derived, the Base portion of Derived got constructed first. This makes sense: logically, a child can not exist without a parent. It’s also the safe way to do things: the child class often uses variables and functions from the parent, but the parent class knows nothing about the child. Instantiating the parent class first ensures those variables are already initialized by the time the derived class is created and ready to use them.

Order of construction for inheritance chains

It is sometimes the case that classes are derived from other classes, which are themselves derived from other classes. For example:

Remember that C++ always constructs the “first” or “most base” class first. It then walks through the inheritance tree in order and constructs each successive derived class.

Here’s a short program that illustrates the order of creation all along the inheritance chain.

This code prints the following:

Constructing A:
A
Constructing B:
A
B
Constructing C:
A
B
C
Constructing D:
A
B
C
D

Conclusion

C++ constructs derived classes in phases, starting with the most-base class (at the top of the inheritance tree) and finishing with the most-child class (at the bottom of the inheritance tree). As each class is constructed, the appropriate constructor from that class is called to initialize that part of the class.

You will note that our example classes in this section have all used base class default constructors (for simplicity). In the next lesson, we will take a closer look at the role of constructors in the process of constructing derived classes (including how to explicitly choose which base class constructor you want your derived class to use).

11.4 -- Constructors and initialization of derived classes
Index
11.2 -- Basic inheritance in C++

18 comments to 11.3 — Order of construction of derived classes

  • WiseFool

    Hi, Alex. Great lesson - I think I clearly understand now how inheritance is implemented by the compiler!  And it makes very good sense in the abstract terms of avoiding coding redundancy, but isn't this pretty expensive in the concrete terms of memory (and maybe CPU) usage?  To use the example of the previous lesson, couldn't there be a case where there were 3 instantiated objects of the same Person!?  One as just a Person, another as an Employee, and a third time as a Supervisor, as well as the 2 instantiated objects of the same Employee, for each instantiated Supervisor?  Or maybe there's still a point that I'm missing that will be explained in a later lesson.

    • Alex

      A Supervisor IS an Employee, which is a Person. Therefore, when you create a Supervisor object, it contains the Supervisor part, plus the Employee part, plus the Person part, all in one object. You don't end up with separate objects for each inherited part.

      It's worth noting that because a Supervisor IS an Employee, which is a Person, you can use a Supervisor anywhere you need a Supervisor, Employee, OR Person. This avoids having to create multiple redundant objects just to have an object of the right type sitting around.

  • Diggi

    Hi Alex

    If a class is inherited privately from a base class, then the contents of the base class constructor executes upon the creation of a derived class object. How is this possible?? If the constructor of a class is private then creation of an object in main() throws an error that constructor is private and cannot be accessed. The same should apply here too, shouldn't it??

    Output:
    base : 0x6dff08
    base : 0x6dff00
    derived : 0x6dff00

    The above program compiles and shows the same address for both base and derived classes when derived class object is created. Please elaborate.

    • nascardriver

      Hi Diggi!

      > How is this possible?
      Private inheritance just means that you can't access the inherited members from outside the class. When creating a @derived object you're not explicitly calling the @base constructor. The @base constructor is called by the @derived constructor, which is public and therefore can be called from @main.

      > The above program compiles and shows the same address for both base and derived classes when derived class object is created.
      The first output was created by the instantiation of @o1, we can ignore that.
      After that you're only creating one object of type @derived so you'll only get one address.

      Suggestions about your code:
      * Don't use 'using namespace
      * You're using the same naming convention for types and functions. That's bad.
      * Initialize your variables with uniform initialization

      References
      Lesson 11.5 - Inheritance and access specifiers

  • Diggi

  • Guozili

    Hi, Alex:
        I have a question when I learn something above MFC. Here is an example with a base class, a derived class and an object:

    .h file:
        class CWinApp
        {
         public:
             CWinApp* m_pCurrentWinApp;
             CWinApp()
             {
                 m_pCurrentWinApp = this;
                 std::cout<< "CWinapp Construnctor\n";
             }
        };

        class CMyWinApp: public CWinApp
        {
         public:
             CMyWinApp()
             {
                 std::cout<< "CMyWinApp Construnctor\n";
             }
        };

    main file:
        int main()
        {
            CMyWinApp theApp;
                    return 0;
        }

    I wonder in this situation, what is the value of m_pCurrentWinApp? Will it point to theApp?

    • nascardriver

      Hi Guozili!

      > Will it point to theApp?
      Yes it does. When constructing @theApp both constructors will be called and @CWinApp::CWinApp will point @m_pCurrentWinApp to the current object.

  • Slava Gusev

    Hi Alex!
    Great tutorials!

    But can you explain plz, how this two parts of derived object store in memory and how they connect with each other?

    Thanks!

    • Alex

      Memory layout isn't specified by the C++ standard and can vary.

      Instead of answering this myself, let me point you to this thread which has some interesting ideas about how to determine this for yourself.

  • Omri

    Hello Alex,
    A thought:
    Discussion up to here is understood assuming a single constructor for each of the parent classes.
    In my view this should be emphasized from the beginning since I was immediately occupied with the dilemma what should occur when a class has more then one constructor? Which one of them will be executed when its child class object is instantiated?
    I have no clue...

    • Alex

      This topic is covered in detail in the next lesson. I've updated the note at the bottom of this lesson to indicate so, in case other readers have the same question.

  • Matt

    In the code before section "Order of construction for inheritance chains", you declare "using namespace std" but you still use "std::cout" in both of your constructors.

  • Vlad

    Hello Alex

    While the derived classes does allow simplification of more complex problems/classes, how does this translate into the executable itself? Will this be an overhead/performance issue?

    And, regarding the next few lessons (I went back here to ask, seems more appropiate), if a derived class is modified -- for example, the constructor, to include the base class in its definition -- how will this impact the performance of the final executable?

    I'm thinking in terms of a 3rd party library, closed source: it comes with a set of functions, but suppose you see potential improvements. You can only add derived classes to it, so how will those improvements fare with the addition of classes, in terms of the binary executable execution, memory, etc if the improvements aren't on a major scale? I hope I managed to get the message.

    • Alex

      Assuming you avoid virtual functions, the only performance overhead may be that your program might use slightly more memory (due to padding issues). However, virtual functions do have a performance impact, since virtual function resolution happens at runtime.

  • Ian

    That was amazing, the inheritance idea really snapped into my head after producing your examples myself. Fantastic stuff Alex. Great Tutorials!

  • Beutifull text, thx!
    ___________________
    my site: http://almaz-job.ru/

Leave a Comment

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