Home C++ Introduction Decisions Loops Input/Output Functions Stack and Heap References Arrays Searching and Sorting Recursion Pointers Character and Strings Structures Classes Inheritance Exceptions Templatess STL Modern C++ Misc Books ----

Inheritance


Contents

In addition to data members having access specifier we can specify an access specifier in the derived class and that tells us what the access ( modified ) would be in the derived class for the base class for someone looking at it from outside. One easy way to remember what the access means is to think of the access as it applies to the public and protected members of the base class. Public inheritance means that the public and protected members of the base class stay as it is. Protected inheritance means that the public and protected members of the base class become protected and private inheritance means the public and protected members of the base class become private.
The concept is somewhat confusing in the beginning and we need to look at some examples.

Public Inheritance



File: i3.cpp
class Base
{
    public:
    int m_public;
    private:
    int m_private;
    protected:
    int m_protected;
};

class Pub: public Base
// note: public inheritance
{
    // Public inheritance means:
    // Public inherited members stay public
    //(so m_public is treated as public)

    // Protected inherited members stay protected
    //(so m_protected is treated as protected)
    // Private inherited members stay inaccessible
    //(so m_private is inaccessible)
    public:
    Pub()
    {
        m_public = 1;
        // okay: m_public was inherited as public
        //m_private = 2;
        // not okay: m_private is inaccessible from derived class
        m_protected = 3;
        // okay: m_protected was inherited as protected
    }
};
int main()
{
    // Outside access uses the access specifiers of the
    //class being accessed.
    Base base;
    base.m_public = 1;
    // okay: m_public is public in Base
    //base.m_private = 2;
    // not okay: m_private is private in Base
    //base.m_protected = 3;
    // not okay: m_protected is protected in Base
    Pub pub;
    pub.m_public = 1;
    // okay: m_public is public in Pub
    //pub.m_private = 2;
    // not okay: m_private is inaccessible in Pub
    //pub.m_protected = 3;
    // not okay: m_protected is inaccessible in Pub
}