17.6 — Adding new functionality to a derived class

In the introduction to inheritance lesson, we mentioned that one of the biggest benefits of using derived classes is the ability to reuse already written code. You can inherit the base class functionality and then add new functionality, modify existing functionality, or hide functionality you don’t want. In this and the next few lessons, we’ll take a closer look at how each of these things is done.

First, let’s start with a simple base class:

Now, let’s create a derived class that inherits from Base. Because we want the derived class to be able to set the value of m_value when derived objects are instantiated, we’ll make the Derived constructor call the Base constructor in the initialization list.

Adding new functionality to a derived class

In the above example, because we have access to the source code of the Base class, we can add functionality directly to Base if we desire.

There may be times when we have access to a base class but do not want to modify it. Consider the case where you have just purchased a library of code from a 3rd party vendor, but need some extra functionality. You could add to the original code, but this isn’t the best solution. What if the vendor sends you an update? Either your additions will be overwritten, or you’ll have to manually migrate them into the update, which is time-consuming and risky.

Alternatively, there may be times when it’s not even possible to modify the base class. Consider the code in the standard library. We aren’t able to modify the code that’s part of the standard library. But we are able to inherit from those classes, and then add our own functionality into our derived classes. The same goes for 3rd party libraries where you are provided with headers but the code comes precompiled.

In either case, the best answer is to derive your own class, and add the functionality you want to the derived class.

One obvious omission from the Base class is a way for the public to access m_value. We could remedy this by adding an access function in the Base class -- but for the sake of example we’re going to add it to the derived class instead. Because m_value has been declared as protected in the Base class, Derived has direct access to it.

To add new functionality to a derived class, simply declare that functionality in the derived class like normal:

Now the public will be able to call getValue() on an object of type Derived to access the value of m_value.

This produces the result:

derived has value 5

Although it may be obvious, objects of type Base have no access to the getValue() function in Derived. The following does not work:

This is because there is no getValue() function in Base. Function getValue() belongs to Derived. Because Derived is a Base, Derived has access to stuff in Base. However, Base does not have access to anything in Derived.

17.7 -- Calling inherited functions and overriding behavior
17.5 -- Inheritance and access specifiers

39 comments to 17.6 — Adding new functionality to a derived class

  • TimCook

    >>Because Derived is a Base, Derived has access to stuff in Base. However, Base does not have access to anything in Derived.

    shouldn't it be 'Because Derived is inherited from base...'?

  • Henrik

    I know in Swift you can make extensions of fundamental types like int or strings (or pretty much any class) and add your own functionality. Like so:

    Is it possible to do something similar in C++ by inheriting from, for example, std::string and implementing my own functionality? (I guess you can't inherit from fundamental types). Or is it against the "style" of C++, and I'm better off just making a whole new class that contains a std::string and methods to modify it?

    Thanks for the tutorials btw, they are really great and easy to follow!

    • nascardriver

      `std::string` isn't a fundamental type, you can inherit from it. Only the types that you don't need to include anything for are fundamental types. You can't inherit from those.

  • choofe

    In the example on this lesson we make a way for public to access the protected member which I want to say is considered private for Base and the derived classes and also is of a base and I assume it should be one important class.
    I wonder isn't it against the rule of thumb of encapsulation?
    I mean we can write a function to modify the protected members,can't we?

    now we are able to modify the m_value in public.
    The creator of the Base may want not m_value to be changed other than in derived class.
    I think a clarify on this issue would be nice in the context as it may be mentioned in comments but you know... people like me may not go through all the comments.

  • Ayrton Fithiadi Sedjati

    I don't understand what you meant in the the last paragraph, "Because Derived is a Base, ...".

    Did you mean "Because Derived is a *child of* Base, ..."?

    Edit: Oh you might have meant "Because Derived is-a Base, ...". Am I correct?

  • David Chiasson

    I what up know by who was hhf previous user to an EMEI and also SN

  • Nirbhay


    Why can't I std::cout 'base.identify()' in the code below?


  • ASP

    Simply said:
    Parents can give and not get back.
    Kids as usual get from Parents and enjoy further.

  • David

    I do not understand the line that says:
    "Now the public will be able to call getValue() on an object of type Derived to access the value of m_value."
    The public what? Maybe you meant that getValue() is available through the public interface of derived?

  • Just Amazing! I just searched "Learn C++" and I landed here. Trust me, this site is one of the best resources for C++.

    Alex, You are doing a great job. Keep it up :)

  • Angmar

    Hi again.

    I don't see why I shouldn't use protected instead of private members, with public inheritances.
    - I don't have to make access functions to read the base classes
    - Being protected, functions outside the classes can't read/write on the members

    Also, do the private members get inherited at all? They are already inaccessible

    • Alex

      Generally you will want to use protected instead of private, unless there's some specific reason you don't want derived classes tampering with the value of a member variable directly. For example, if you have two member variables that need to have correlated values, allowing derived classes direct access could result in errors being made. In such a case, it's better to force even derived classes to use a public (or protected) interface.

      Private members are inherited, they're just inaccessible from the derived class.

      • tip

        What if m_value in the parent Base class is private and we create the child  Derived class using the Base class constructor to set a value for m_value in the Derived class.
        Now m_value in Derived should not be accessible, because it is private, can we still define a getValue() or setValue() for m_value? Do we have to use the parent class getters/setters?

        • Alex

          > can we still define a getValue() or setValue() for m_value? Do we have to use the parent class getters/setters?

          Assuming you did the inheritance publicly:
          * If the base class already has public getters/setters, there is no need to redefine those functions in the derived class, as they will still be accessible via the base class even with a derived object.
          * If the base class does not have public or protected getting/setters, there is no way to access this variable directly from the derived class.

  • Pedro

    Thank you very much for this awesome tutorial!!!
    Do you have any other tutorials of any other languages???
    If not, would you consider doing? C#, Java or Python would be great! :)
    Great tutorial, very complete and well explained!!!
    Thank you very much!!!

    • Alex

      You're welcome. I don't know any other languages well enough to teach, and even if I did, I don't think I'd have enough time to write another site. There's still so much about C++ to write about that I haven't gotten to yet!

      • Angmar

        > There’s still so much about C++ to write about that I haven’t gotten to yet!
        This is already a 1600 pages worth of content! Would you like to have a section saying stuff like "what we haven't discussed yet" or "where to go from here"? I'd personally very much like to see an "Introduction to CMake" or something similar. I like your way of delivery, it's very intuitive to me.

        And as always, I've very grateful to your tutorial. It's one of the very few ones that are up-to-date with the latest C++.

  • Omri

    Right, preecompiled can be both ( contradictory!) understood as:
    a. not yet compiled
    b. already compiled
    Actually, I think there is no way to decide which is intended other than knowing beforehand... Or perhaps "precompiled" is a jargon shorthand for "previously compiled"...
    This is quite different from ordinary use of pre ( like prehistory) which means before (as before history).
    No end to confusion possibilities...

    As per:
    "Yes, by precompiled, I mean compiled before being distributed to the user of the library."
    Do youvmean:
    "Yes, by precompiled, I mean compiled and added as such to the library before distribution of the library to users."

    • Alex

      Yeah, I guess it is a little weird. Precompiled is a term in computer science (usually used in the context of precompiled headers) meaning that something was already compiled. So rather than "before being compiled", it means "compiled before".

      And by precompiled I mean, "the library code files were compiled by the library creator, and distributed in compiled form to customers".

  • Omri

    "The same goes for 3rd party libraries where you are provided with headers but the code comes precompiled."
    My understanding was that the code in a library comes ***compiled*** and is only linked to the user project when called.
    I will happily be advised.

  • Carlos

    I am following your tutorials and I feel the need to write you just thanking this awesome content and the effort you did to do it. Thank you thousand times! hope existed more people like you :)

  • roy

    hi,good teacher..
    cplus is very difficult, but by reading a lot of things become clear,
    but huge contents need to remember,
    so i think cplus need a revolution to make it less errorprone! i used c 12years.thks

  • dazedbrain

    Because Derived is a Base, Derived has access to stuff in Base.

    I thought "Because Derived is derived from Base" would make more sense.

  • Reaversword

    I’ve been thinking about this, trying to reach a "logical-intuitive" example.

    This is my example, but it includes some questions that get this topic a little bit "out of the limits", I think.

    4 classes:

    Grandfather (60 year old man, owner of a shop)
    Father (32 years old man, co-owner of a shop)
    Son1 (8 years old boy, still doesn’t know exactly what he does, no dental caries diagnosed).
    Son2 (10 years old boy, still doesn’t know exactly what he does, dental caries diagnosed).

    Grandfather has:
    dentures (private), safeDepositBox (protected), tv (protected), candies (public).

    Father has access to all except dentures.

    But, I confess I’m unable to get this working (cause I'm looking for the limits):

    *This lesson answers question 1.

    1*) How can Father "private" the son to get access to safeDepositBox, but let him use tv?
    (This would be get 2 base protected members, and get one private, and other still protected, but this would be per-member, and not per-class).

    2) How can Father "private" the Son2 to get access to candies (because dental caries), but still be able to offer it to Son1?
    (This would be a member-private for one derived class, but available for the other derived one).

    3) How can Father "private" the Sons to get access to candies (because dental caries), but still be able to offer it to public?
    (This would be a member-private for derived classes, but available for the public).

    Are any of this two last cases possible?. Or this is go to much out of the limits / rules?.

    • Alex

      > How can Father "private" the son

      I don't know what this means. Are you asking how Son can derived from Father, keeping safeDepositBox private but keeping tv protected? If Father doesn't want anybody to inherit access to the safeDepositBox by default, he could redefine it as private. But the Son could still override it.

      Essentially, access controls are there to help enforce good encapsulation, not to strictly keep derived classes in or out.

      • Reaversword

        I was asking how Father prevent Son access to safeDepositBox, but still leaves him use tv. But this is perfectly answered here.

        Father just redeclares safeDepositBox as private , and do nothing with tv (because is already declared as "protected" by Grandfather).

        So, interesting ones (and I think a little bit out of limits) are 2) and 3).

  • Thanks again for this absolutely wonderful tutorials!

  • Kinten

    ok, the only diference in private and protected inheritance is while making multiple inheritances? say yo got:

    base --> derived1 --> derived2 (diagram)

    if derived1 does Private inheritance then derived2 can't acces anything from base class, otherwise if I make derived1 Protected derived2 will have acces, but not the program.
    I am right?

    • Kinten

      Multiple inheritance was't the right word, it shold be "multiple times derived"

    • If derived1 does private inheritance, than derived2 can't access anything from the base class, as you say.

      If derived1 uses protected inheritance, then public and protected members in the base class become protected in derived1. This means that they can be accessed by derived2. Note that neither derived1 nor derived2 can access private members in base.

      In reality, it is pretty uncommon to see private and protected inheritance. Almost all of the inheritance you see is done via public inheritance.

Leave a Comment

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