11.4 — Constructors and initialization of derived classes

In the past two lessons, we’ve explored some basics around inheritance in C++ and the order that derived classes are initialized. In this lesson, we’ll take a closer look at the role of constructors in the initialization of derived classes. To do so, we will continue to use the simple Base and Derived classes we developed in the previous lesson:

With non-derived classes, constructors only have to worry about their own members. For example, consider Base. We can create a Base object like this:

Here’s what actually happens when base is instantiated:

  1. Memory for base is set aside
  2. The appropriate Base constructor is called
  3. The initialization list initializes variables
  4. The body of the constructor executes
  5. Control is returned to the caller

This is pretty straightforward. With derived classes, things are slightly more complex:

Here’s what actually happens when derived is instantiated:

  1. Memory for derived is set aside (enough for both the Base and Derived portions)
  2. The appropriate Derived constructor is called
  3. The Base object is constructed first using the appropriate Base constructor. If no base constructor is specified, the default constructor will be used.
  4. The initialization list initializes variables
  5. The body of the constructor executes
  6. Control is returned to the caller

The only real difference between this case and the non-inherited case is that before the Derived constructor can do anything substantial, the Base constructor is called first. The Base constructor sets up the Base portion of the object, control is returned to the Derived constructor, and the Derived constructor is allowed to finish up its job.

Initializing base class members

One of the current shortcomings of our Derived class as written is that there is no way to initialize m_id when we create a Derived object. What if we want to set both m_cost (from the Derived portion of the object) and m_id (from the Base portion of the object) when we create a Derived object?

New programmers often attempt to solve this problem as follows:

This is a good attempt, and is almost the right idea. We definitely need to add another parameter to our constructor, otherwise C++ will have no way of knowing what value we want to initialize m_id to.

However, C++ prevents classes from initializing inherited member variables in the initialization list of a constructor. In other words, the value of a variable can only be set in an initialization list of a constructor belonging to the same class as the variable.

Why does C++ do this? The answer has to do with const and reference variables. Consider what would happen if m_id were const. Because const variables must be initialized with a value at the time of creation, the base class constructor must set its value when the variable is created. However, when the base class constructor finishes, the derived class constructors initialization lists are then executed. Each derived class would then have the opportunity to initialize that variable, potentially changing its value! By restricting the initialization of variables to the constructor of the class those variables belong to, C++ ensures that all variables are initialized only once.

The end result is that the above example does not work because m_id was inherited from Base, and only non-inherited variables can be initialized in the initialization list.

However, inherited variables can still have their values changed in the body of the constructor using an assignment. Consequently, new programmers often also try this:

While this actually works in this case, it wouldn’t work if m_id were a const or a reference (because const values and references have to be initialized in the initialization list of the constructor). It’s also inefficient because m_id gets assigned a value twice: once in the initialization list of the Base class constructor, and then again in the body of the Derived class constructor. And finally, what if the Base class needed access to this value during construction? It has no way to access it, since it’s not set until the Derived constructor is executed (which pretty much happens last).

So how do we properly initialize m_id when creating a Derived class object?

In all of the examples so far, when we instantiate a Derived class object, the Base class portion has been created using the default Base constructor. Why does it always use the default Base constructor? Because we never told it to do otherwise!

Fortunately, C++ gives us the ability to explicitly choose which Base class constructor will be called! To do this, simply add a call to the base class Constructor in the initialization list of the derived class:

Now, when we execute this code:

The base class constructor Base(int) will be used to initialize m_id to 5, and the derived class constructor will be used to initialize m_cost to 1.3!

Thus, the program will print:

Id: 5
Cost: 1.3

In more detail, here’s what happens:

  1. Memory for derived is allocated.
  2. The Derived(double, int) constructor is called, where cost = 1.3, and id = 5
  3. The compiler looks to see if we’ve asked for a particular Base class constructor. We have! So it calls Base(int) with id = 5.
  4. The base class constructor initialization list sets m_id to 5
  5. The base class constructor body executes, which does nothing
  6. The base class constructor returns
  7. The derived class constructor initialization list sets m_cost to 1.3
  8. The derived class constructor body executes, which does nothing
  9. The derived class constructor returns

This may seem somewhat complex, but it’s actually very simple. All that’s happening is that the Derived constructor is calling a specific Base constructor to initialize the Base portion of the object. Because m_id lives in the Base portion of the object, the Base constructor is the only constructor that can initialize that value.

Note that it doesn’t matter where in the Derived constructor initialization list the Base constructor is called -- it will always execute first.

Now we can make our members private

Now that you know how to initialize base class members, there’s no need to keep our member variables public. We make our member variables private again, as they should be.

As a quick refresher, public members can be accessed by anybody. Private members can only be accessed by member functions of the same class. Note that this means derived classes can not access private members of the base class directly! Derived classes will need to use access functions to access private members of the base class.


In the above code, we’ve made m_id and m_cost private. This is fine, since we use the relevant constructors to initialize them, and use a public accessor to get the values.

This prints, as expected:

Id: 5
Cost: 1.3

We’ll talk more about access specifiers in the next lesson.

Another example

Let’s take a look at another pair of classes we’ve previously worked with:

As we’d previously written it, BaseballPlayer only initializes its own members and does not specify a Person constructor to use. This means every BaseballPlayer we create is going to use the default Person constructor, which will initialize the name to blank and age to 0. Because it makes sense to give our BaseballPlayer a name and age when we create them, we should modify this constructor to add those parameters.

Here’s our updated classes that use private members, with the BaseballPlayer class calling the appropriate Person constructor to initialize the inherited Person member variables:

Now we can create baseball players like this:

This outputs:

Pedro Cerrano

As you can see, the name and age from the base class were properly initialized, as was the number of home runs from the derived class.

Inheritance chains

Classes in an inheritance chain work in exactly the same way.

In this example, class C is derived from class B, which is derived from class A. So what happens when we instantiate an object of class C?

First, main() calls C(int, double, char). The C constructor calls B(int, double). The B constructor calls A(int). Because A does not inherit from anybody, this is the first class we’ll construct. A is constructed, prints the value 5, and returns control to B. B is constructed, prints the value 4.3, and returns control to C. C is constructed, prints the value ‘R’, and returns control to main(). And we’re done!

Thus, this program prints:

A: 5
B: 4.3
C: R

It is worth mentioning that constructors can only call constructors from their immediate parent/base class. Consequently, the C constructor could not call or pass parameters to the A constructor directly. The C constructor can only call the B constructor (which has the responsibility of calling the A constructor).


When a derived class is destroyed, each destructor is called in the reverse order of construction. In the above example, when c is destroyed, the C destructor is called first, then the B destructor, then the A destructor.


When constructing a derived class, the derived class constructor is responsible for determining which base class constructor is called. If no base class constructor is specified, the default base class constructor will be used. In that case, if no default base class constructor can be found (or created by default), the compiler will display an error. The classes are then constructed in order from most base to most derived.

At this point, you now understand enough about C++ inheritance to create your own inherited classes!

Quiz time!

1) Let’s implement our Fruit example that we talked about in our introduction to inheritance. Create a Fruit base class that contains two private members: a name (std::string), and a color (std::string). Create an Apple class that inherits Fruit. Apple should have an additional private member: fiber (double). Create a Banana class that also inherits Fruit. Banana has no additional members.

The following program should run:

And print the following:

Apple(Red delicious, red, 4.2)
Banana(Cavendish, yellow)

Hint: Because a and b are const, you’ll need to mind your const’s. Make sure your parameters and functions are appropriately const.

Show Solution

11.5 -- Inheritance and access specifiers
11.3 -- Order of construction of derived classes

138 comments to 11.4 — Constructors and initialization of derived classes

  • ammawn

    For the Quiz question, would you consider it better to overload operator<< in the base class (Fruit) instead of each derived class (Banana, Apple) since some classes(Banana) may only have the members of the base class (Fruit) and if you added another derived class where the members are the same as the base class another operator<< function would not need to be written since the base class will account for it.

  • Hakeem A Thomas

    Hello, so after this lesson I was trying to figure out an issue I had with the quiz question. I didn't want to reuse code for overloading operator<<. So to no avial I forward declared the Apple and Banana to use in a if statement(*line 27*). I was wondering if there was a way to use the class objects in my if statement(Or any other option) to avoid reuse.

    • nascardriver

      Pass non-fundamental types by reference.

      You can solve this by using `virtual` functions, which are covered in the next chapter

  • Victor Keilhack

    I have three questions, which I tried to answer to myself, but I'd like to know your opinion on them.
    1. Calling the constructor of the parent is just like a delegating constructor then?
    2. Can a derived class be a friend class of its parent? Can it then access the private members of the parent? Is that even sensible?
    I tried it out and it worked. There are some weird nuances to it though: In the definition of my operator<< function, I couldn't use the private members of the parent, if the function was only a friend of the child. It had to be a friend to the parent aswell (Makes sense, because you said once, that a friend's friend is not a friend). Same is true for the child class of the child of a base class: it needs to be friended with the base aswell to use its private members. This would be madness, so I suppose it is better to stick with the public access-functions. What do you say?
    Edit: I just read about the protected Access specifier in the next chapter and that makes much more sense.
    3. I noticed while testing, that a declaration of a friend is not a forward declaration. In the example below, I had to forward-declare Child before I could use it as a function parameter in the function prototype inside Parent. The friend declaration didn't suffice for the function to know, that there is a class named Child somewhere. Why is that?

    • nascardriver


      1. Somewhat yes, you're delegating construction to the parent. Unlike delegation to another constructor of the same class, you are allowed to initialize members of the child even if you call a parent constructor.

      2. It seems you already figured this out.

      3. I don't know.

  • Mn3m

  • David

    Hi,in your example,I think you forget to include the iostream header file.Otherwise,you can't use the object cout.

  • Matt

    One note for the author - in your solution for this quiz the constructor for Apple takes non-const parameters in contrast to the constructors for Banana and Fruit. I believe you intended for them to be const.








  • Anastasia

    my idea was that since both Apple and Banana are Fruit, then it should be enough to overload `operator<<` only for Fruit and then add additional overloadings for the (child) classes than need additional information printed (Apple case). Well, it works... But why do I need to explicitly convert Apple to Fruit (line 62) if Apple 'is-a' Fruit and there's already `operator<<` overloaded for Fruit? If I don't cast explicitly it goes into infinite recursion and gives me a Seg.fault... And overall is this approach acceptable (overloading operators for parent classes and using them for childs)?

    *it's not a valid quiz solution, because it doesn't specify whether it's a Banana or an Apple and doesn't respect the output formatting.

    • > why do I need to explicitly convert Apple to Fruit
      You answered your own question. If you don't cast it, you're recursively calling `operator<<(std::ostream&, const Apple&)`. You can't expect line 70 to call `operator<<(std::ostream&, const Apple&)` and line 62 (without the cast) to call `operator<<(std::ostream&, const Fruit&)`. They're the same thing without the cast.

      > is this approach acceptable
      Yes. With printing and similar things you have to be careful, as the parent could change its output format and mess up the child. This isn't a problem when you overload the assignment operator for example (Unless you use it for something weird).
      As long as you're using a comma separated list and stick to it, your method is fine.

      • Anastasia

        > If you don't cast it, you're recursively calling `operator<<(std::ostream&, const Apple&)`.
        Yes, that's what clang told me. But it makes no sense... I was reasoning this way: ostream doesn't know how to print apples yet, so if I do `stream << apple` it will look for something it knows how to print, which means Fruit!
        Well, I'd understand if one overloaded `operator<<` coulnd't call another overloaded `operator<<`, but it can (the fact that it works with casting shows it). Still confusing...

        > As long as you're using a comma separated list and stick to it, your method is fine.
        Thank you.

        • Operators are just functions with fancy syntax.

          • Anastasia

            It makes more sense in your example, but still. Maybe it's wrong way of thinking about derived classes as being half-parent, half-child (each part being equally important)? Or I should start taking into consideration that the child-half always takes precedence if there's some possible ambiguity.

      • hellmet

        Somehow, I felt the cast was the way to go! It felt intuitive (why, I don't know)! But after I had a look at the solution and this discussion, I started to think more.

        How does this cast actually happen? I am converting a bigger datatype into a smaller one. Clearly, I am bound to lose information that is in the derived class, but is it guaranteed to be _exactly_ that and no more?

        If the base class is managing a heap-allocated resource, and I cast a derived class to the base one, what is happening? I added a copy constructor and an assignment overload to Fruit to see what happens.

        Hmmm.... The output is different! But makes sense! MSVC is creating a copy _before_ the output, perhaps as an optimization, whereas clang seems to be generating the copy at the point of the actual call.

        All that aside, a cast seems to call a copy constructor (I cannot reason about that, since the argument is a Fruit in the copy-constr, but we are passing an Apple and Bananna... which should cast, so implicit casts are possible from child to parent? :/ ).

        Clearly, for a cast from base to derived to be possible, we need to define one, as that is the only way the compiler can figure out how to 'add' more data to the smaller base class and make the derived object.

        This was fun!

        • nascardriver

          First off, you should be casting references. That way you're not creating any copies or losing information at all.

          > I am bound to lose information that is in the derived class, but is it guaranteed to be _exactly_ that and no more?
          Yes, you're losing the derived portion. There's a lesson about this in chapter 12 ("Object slicing").

          > If the base class is managing a heap-allocated resource, and I cast a derived class to the base one, what is happening?
          The base's copy constructor performs the copy. If it's properly implemented, it should perform a deep copy and everything is fine.

          > a cast seems to call a copy constructor
          Constructors with a single parameter are converting constructors. Unless they're `explicit`, they will be used for conversions.

          > Clearly, for a cast from base to derived to be possible, we need to define one
          For now, yes, but not after chapter 12 :)

          • hellmet

            > static_cast<const Fruit&>(bn)
            That works! Damn I didn't know that was possible! A copy is not made, so the compiler just 'access' the required parts (that are in the base class) to more or less make it look like there's a Fruit object there. Very nice indeed!

            > Copy constructors with a single parameter are converting constructors.
            Ahh I seem to have failed to completely internalize the discussion in the lesson 9.13. Need to revise!

            How do I make sure I do not forget these? Does it only come with experience?

            Thank you very much for the detailed explanation!

            • nascardriver

              > Copy constructors with a single parameter are converting constructors.
              "Constructors", not "Copy constructors" is what I meant to say.

              > How do I make sure I do not forget these? Does it only come with experience?
              You'll forget a lot of things while you're actively learning. Try to apply what you learned when you write new code, or apply it to code you already wrote. As long as you keep using it, you won't forget it.

              • hellmet

                > "Constructors", not "Copy constructors" is what I meant to say.
                Yeah I get what you meant, in this case, this constructor happens to be a copy constructor, and also works as a converting one too!

                Also, I noticed it just now, Clang seems to complain while compiling the code above ...

                Thank you for your suggestion and motivation!
                After all the lessons, is there a final assignment or project where I can test all of these skills out?

                • nascardriver

                  > After all the lessons, is there a final assignment or project where I can test all of these skills out?
                  Nope. Try to think of something yourself. Ideally something that's actually helpful for your daily computer use so you stay motivated.

      • salah

        Hi, as far as I know, when converting ,for example, int to double  : static_csat<double>(int), the variable of type int become double, it makes sence.But when we convert object to another object how the compiler would deal with this situation?  static_cast<Fruit>(apple). Fruit has two variables. Whereas, Apple have three, what will happens here ?

        • nascardriver

          `Apple` is a `Fruit`, so we can cast `Apple` to `Fruit`. If we do that, we're losing everything that `Apple` has that is not in `Fruit`. That is, `m_fiber` is lost in the cast. As you can imagine, this isn't good. We talk more about this later.

  • Nirbhay


    In the above code, please explain the part:


    2. why did Alex return a 'const' string and what does '&' mean in 'std::string&' below.

    const std::string& getName() const { return m_name; }


  • DecSco

    Nitpicking level >9000:
    The solution produces a space between "Apple" and the opening parentheses, whereas the given output does not have that space. Same for "Banana".
    Thanks for all the effort that went into this site, Alex!
    And thanks to Nascardriver for answering almost every question in the comments!

  • A

    Hello! Would it be acceptable to make the std::ostream function a friend of the Apple class, and use m_fiber directly rather than through an access function?

  • Ben K

    I've noticed that the solution to this quiz works if I have the classes and operator<< functions defined in my main.cpp file, but not if I have them in my source.h file. Why is that? Otherwise, it throws an error about operator<< being defined multiple times, even though the two definitions have different second arguments.

    As for putting it in the source.h file, I had to declare the operator<< methods inside of the class as friend functions. Why exactly is this a bad idea?

    • Without knowing your code, I'm guessing that you're including "source.h" in multiple files. Since the contents of the header are copied to the includer, you'll end up with multiple definitions.
      Definitions don't belong in header files, they belong in source files. Put the class declaration in "source.h" and the function definitions in "source.cpp".

      > Why exactly is this a bad idea?
      `operator<<` now has full access to all private members of your class and could make changes that weren't normally possible by using access functions.

  • Tom

    Hi, Alex
    In my understanding, const objects should use const member functions, right? Though in the quiz solution, why are

    are const functions, but

    is not a const function. More strange to me, it still works. Thus I tried to remove the const in the above two functions, then it gave me compile error. What the difference between the getName and getFiber functions?

    • `getFiber` is const.

      The const in the other 2 functions refers to the return type. Since returning a non-const reference would grant the caller direct access to the members, they can't return a non-const reference.
      `getFiber` doesn't need to return a reference, because it's returning a fundamental type (`double`).

  • Dimbo1911

    Good morning guys! Any remarks on this code? Thank you for your time :)

    • Good morning!

      - Avoid abbreviations. They increase the time required to read your code. Code is more often read than written.
      - Use single quotation marks for characters (Line 51, 60).

  • Paulo Filipe

    Here's my Quizz solution, pretty identical to the exercise's solution:

    I've also learned this neat way of writing initializer lists that look very nice (at least to me) while navigating through Stack Overflow:

    I really find it easy to read and it aligns excellent!

  • musaka

    Isn't Apple's getFiber() method from the quiz solution redundant?

    • No. It exposes the value of @m_fiber without allowing overrides.
      @operator<< shouldn't be a friend of @Apple. That way the code makes more sense.

      • Alex

        One might reasonably argue that making operator<< a friend and having it directly access m_fiber is better than having it be a non-friend and requiring the class to have an otherwise unneeded accessor.

        In any case, I've defriended the operators in the solution since these classes do have accessors as part of their interfaces.

  • hassan magaji

    Hi Alex,
    i found a couple of typos:

    1) in the first paragraph: "...the simple Base and Derived __class__ we developed...", should be "classes"?.

    2) "...and only non-inherited variables can be __changed__ in the initialization list...",  as applied to member initialization list, i think it should be "initialized".

    3) "...We make our __members__ variables private again..." should be "member".

    finally i need some clarification for this:

    it delegates the parent's constructor and also initialized m_cost which is not in agreement with a quote in lesson 8.6(-overlapping and delegating constructors) which states thus: "...constructor that delegates to another constructor is not allowed to do any member initialization itself. So your constructors can delegate or initialize, but not both."

    i know that derived classes have some specific rules but it just kinda puzzled my head and cant wait for your reply.

    thanks for the hardwork.

    • Hi Hassan!

      The statement in lesson 8.6 only concerns calls to constructors in the same class, not constructors of a parent class.
      The constructor you showed calls a constructor of the parent, which is fine. It couldn't call another constructor of @Derived and keep the initialization of @m_const.
      This is because constructors are assumed to fully initialize the class (ie. initialize all members). Since a parent class constructor can't initialize the child's members, you can initialize them yourself.

      • hassan magaji

        finally unraveled, thank you nas...
        another question i you would'nt mind :
        can a derived class call it parent's base class constructor? I mean (p1 -> p2 -> p3)
        can p3 call p1's constructor(by skipping    its immediate parent class to its parent's base class).

        thank you once again you've both been clearing obstacles for us throughout our learnC++ journey.

    • Alex

      Thanks for pointing out the typos!

  • lucieon


    What purpose does const serve in this case?

    Is it any different than setting the data members of Fruit and Apple classes constant?

    • const isn't usually applied to non-reference, non-pointer variables, because all it does is prevent you from accidentally modifying them, which you shouldn't do anyway if you're paying attention to what you're doing.

      In this case, const prevents changes to @a and @b. If you were to declare @Apple's and @Banana's members const, you'd loose the ability to create non-const @Apples and @Bananas.

  • lucieon


    In this code if you use uniform initialization to call Base constructor, what's the difference?
    So this;

    becomes this;

    It's giving me the same answer when I create

    in main() but I don't know what's exactly happening.

    • Implicit casts are prevented

  • Jörg

    Hi, is there a reason to not make the access functions of the Fruit class return const references? also merry christmas :)

  • Hunter

    There is a typo under the header "Another Example."

    The text currently reads: "Let’s take a look at another pair of class we’ve previously worked with."

    "Class" should be replaced with "classes."

    Keep up the good work!

  • Hi,

    in the solution here:

    I am just concerned about memory wastage if we add more fruit and need to keep redefining the Base class....

    • Alex

      I got 56, 64, 56. Banana doesn't take any additional memory over Fruit, and Apple only does because it has an added double member.

  • Arumikaze

    Hello! I have completed the quiz in separate files. Could you please give me feedback on my code and if I did it correctly? Thank you!








    Sorry for the long post.

    • Hi Arumikaze!

      * Default arguments should be in the header. If you write a library, the person using the library does only have the source code of the headers files. But they should know about default arguments.
      * Wherever you're accepting an @std::string as a parameter or returning one, you should do so by const reference.
      * main.cpp:9,12: Uniform initialization
      * Since @Banana's constructor should be a copy of @Fruit's constructor, you can inherit the constructor so you don't have to write it again.

      • Jon

        HI nascardriver, does this using statement do anything except inherit the constructor? What if there was more than one constructor in the Fruit class? And can you only "use" the constructor of the base class, or any other class too?

        Hopefully this covered in a future lesson? :)

        • > does this using statement do anything except inherit the constructor?

          > What if there was more than one constructor in the Fruit class?
          You get all.

          > And can you only "use" the constructor of the base class, or any other class too?
          > Also, if there was one or more levels of subclass down from Banana that inherited publicly, could you also write "using Fruit::Fruit" for those classes?
          You can only inherit constructors of the direct parent.

          > Hopefully this covered in a future lesson?
          I don't know.

      • Jon

        Also, if there was one or more levels of subclass down from Banana that inherited publicly, could you also write "using Fruit::Fruit" for those classes? Or does it only work for the immediate parent?

  • Endcity

    I have considered the above example and I think constructor of derived class will execute lastly but member initializer lists of derived class will execute first so that int a can pass through C,B to A. Is that right ?

  • Mau


    thanks for the great tutorial and also a question.

    I got a bit confused by all those constructors being called, but despite that, in the end there is only one object on the call stack, isn't it?

    • nascardriver

      Hi Mau!

      There are no objects on the call stack, there are addresses on the call stack.
      Assuming you're talking about regular objects, there's only one object, no matter how many constructors where called.

  • Ran

    My code is less efficient than Alex's solution because I re-write
    getName() twice in the derived class. A better solution is to put
    getName() in the base class.

    I tried to do Alex's style, but I was struck with the constructor.

    Putting the user-defined initial values in the derived class's
    constructor is what I learned from Alex's solution.

    • nascardriver

      Hi Ran!

      * @m_name is never initialized not used.
      * @Banana doesn't have a color on it's own, it's using the default value, it works, but it's not nice.
      * Uniform initialization is preferred.
      * std::strings should be passed and returned by reference

  • xjuggy

    I initially set my classes and member functions up in a similar fashion to yours, Alex, and all was well.  Then I decided to experiment with the "never reuse code" mantra:


    Thus, I tried to create a Fruit overloaded "<<" operator to handle the getName/getColor portion of the output.

    In the course of doing so, I realized I (a) probably overly complicated my code and (b) ended up with what I deduced was a recursive function call to infinity.

    Question: Is there a way to call a specific version of the overloaded "<<" operator?

    My code which prints Apple until a stack overflow:

    • xjuggy

      Well, I made it to lesson 11.6a, and found the answer there: "static_cast"

      • Alex

        There's a better answer. Remove the overloaded operator<< functions for Apple and Banana. You don't need them.

        Without them, Fruit::operator<&lt will be called, and that function already has everything it needs to print the Fruit's name and color.

  • Ada

    how is this? i used a different main function from the one given in the quiz

    using namespace std;

    class Fruit
            string m_name;
            string m_color;
            Fruit(string name=" ",string color=" ")
              string getName()
               const {return m_name;}
              string getColor()
               const {return m_color;}

    class Apple:public Fruit
            double m_fiber;
            Apple(string name=" ",string color=" ",double fiber=0.0)
              : Fruit(name,color), //call Fruit(string,string) to initialize these fields
              double getFiber()
               const {return m_fiber;}
    class Banana:public Apple
            int m_best;
            Banana(string name=" ",string color=" ",double fiber=0.0,int best=0.0)
              : Apple(name,color,fiber), //call Apple(string,string,double) to initialize these fileds
              int getBest()
               const {return m_best;}

    int main()
        const Apple a("Red delicious", "red", 4.2);

        const Banana b("Cavendish", "yellow");

        return 0;

    Red delicious

  • Alexxx

    About that part:
    Note that it doesn’t matter where in the Derived constructor initialization list the Base constructor is called -- it will always execute first.
    If i do

    then i get warnings

    Worth noting in the same paragraph?

    • Alex

      This warning will occur (for compilers that support it) any time you initialize class members in a different order than in which they are defined in the class (or, in this case, with the base class constructor called first). It's not really specific to construction of derived classes, but rather to all classes.

  • AMG

    Could you please tell me if in my version "const" is redundant in class constructors and access functions.

    Thank you very much.

Leave a Comment

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