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
Instantiating 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:
Constructing B:
Constructing C:
Constructing D:


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
11.2 -- Basic inheritance in C++

45 comments to 11.3 — Order of construction of derived classes

  • Yousuf

    Assume that we have two classes A, and B. A is parent class, and B is child class. We usually know that B inherits the member functions and member variables from A, and now we know that when B gets instantiate it instantiates A first. Then why can't we say that B inherits the constructor of A?

  • Gamer_to_be

    >>C++ allocates memory for Base, then calls Base’s default constructor to do the initialization.

    Something that has confused me alot :
    Does this mean allocates memory for object 'base' or class itself 'Base' in the code below?
    Is this allocation of memory done by C++ compiler? also does this allocation mean JUST allocating memory for all member variables of a class or is it more than that?

    Because when I print the address of a class, this address is the same address of the first member variable (in order) in a class(if there is one)? What if there is no member variables in a class then what the address of a class refer to and what memory allocation means in this case?

    • nascardriver

      A `class` only describes an object. It doesn't have an address, it doesn't take up any memory. What has an address and takes up memory is an instance of the `class`, ie. `base`. The memory is allocated at run-time (But the compiler already knows how much memory it will need to store a `Base` instance).
      The address of the first member is not always the same as the address of the object.

  • salah

    "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".

    could you please explain a little bit how the process happens?
    do you mean that the derived object will be splited into two different parts in the memory?

  • Hansorg

    I am having problem visualizing the derived class which is described as merger of the base class and the derived class. Can you please tell me how things actually work in reality? Are the members of the base class copied into the derived class? How do things work 'under the hood' during inheritance?

    • nascardriver

      You're right. The members of the base class are copied into the derived class (Before the members of the derived class).

      • kavin

        Hi, what you said is opposite to the info in this chapter-"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."
        Which one is correct ?

        • nascardriver

          I'll leave this to Alex, because that quote made me unsure. As I understand it, the diagram should be

          In words, the derived class starts with its base portion (As a subobject), followed by the derived portion.

          • Alek

            Hey, Nascar  you are still not sure about what actually happens when we inherit ?
            copying happens or not ?
            I personally think it can't be a copy. because when A inherits a member-function from B if the definition is copied into the subclass and we also declare a version of that ourselves it is like we are breaking ODR. also the redundancy will happen anyway, because instead of creating new variables we merely copied some from another class.
            but I still can't imagine how they are resolved.
            thanks for all your great content!

  • bkelly

    From the top of this page:

    first line:  I understand that the constructor accepts an argument to set the value of the member variable.
    second line:  Please explain what the :m_cost(cost) does.

  • J Gahr

    Hey Alex, why don't you use printf() in places where it might be less typing than using std::cout? Just curious about that, since I don't remember seeing it used yet in this tutorial.

    • Alex

      printf() is C-style output, and this tutorial doesn't really cover much C, even though it's technically available from within C++.

    • Muhammad Azeem Rao

      Ya printf() is a c-style and not of c++, in c++ we can write just cout instead of std::cout for this you have to just include #include <iostream> library at the top, and can use each line without std::cout. I think it is not a better approach to write std:: on each line before cout.

      • @std::printf is part of C++ and it's perfectly fine to use it.
        If you want to use "cout" instead of "std::cout" you need a using statement. This is discouraged as is can cause name collisions.

        • Muhammad Azeem Rao

          Basic-cout is an object of type ofstream in c++ used to display unformatted string while printf is a function mainly in c used to display formatted string, ... - For one, printf() is essentially a C function and cout() is a C++ function, and they both use completely different syntax.

  • Endcit

    How about destructor's order?

    • nascardriver

      Hi Endcit!

      Destructors are called in the reverse construction order. Taking the example above, construction and destruction of @D looks as follows:

      • J Gahr

        Is it also universally true that the last object to be declared in the file is the first to be destructed?

        • Sorry, I don't quite get it, can you provide sample code?

          • J Gahr

            • > Is it also universally true that the last object to be declared in the file is the first to be destructed?
              Not in the file, because you can swap functions holding location variables around however you want. But variables in the same scope, yes.

              * Don't use "using namespace"
              * Initialize your variables with uniform initialization
              * Use @std::printf rather than @printf
              * Don't mix @std::cout and @std::printf unless you have a reason to do so

  • 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??

    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

      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
             CWinApp* m_pCurrentWinApp;
                 m_pCurrentWinApp = this;
                 std::cout<< "CWinapp Construnctor\n";

        class CMyWinApp: public CWinApp
                 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?


    • 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:

Leave a Comment

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