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

Private Inheritance



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

class Pri: private Base
    // note: private inheritance
{
        // Private inheritance means:
        // Public inherited members become private
        //(so m_public is treated as private)
        // Protected inherited members become private
        //(so m_protected is treated as private)
        // Private inherited members stay inaccessible
        //(so m_private is inaccessible)
        public:
        Pri()
        {
            m_public = 1;
            // okay: m_public is now private in Pri
            // m_private = 2;
            // not okay: derived classes can't access
            //private members in the base class
            m_protected = 3;
            // okay: m_protected is now private in Pri
        }
};

class Derived : public Pri
{
   public:
   Derived()
    {
        //Compiler error
        //m_protected = 5 ;
    }
};


int main()
{
    // Outside access uses the access specifiers of the class being accessed.
    // In this case, the access specifiers of base.
    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
    Pri pri;
    //   pri.m_public = 1;
    // not okay: m_public is now private in Pri
    //pri.m_private = 2;
    // not okay: m_private is inaccessible in Pri
    //pri.m_protected = 3;
    // not okay: m_protected is now private in Pri
}


Exercise

Find all the access errors in the below program.

File: ex2.cpp
class Base
{
    private:
        int m_private ;
    protected:
        int m_protected ;
    public:
        int m_public;
        Base()
        {
            m_private = 3 ;
        }
};

class Derived: public Base
{
  private:
    int p_var2 ;
  protected:
    int p_var1 ;
  public:
    int p_var3 ;
  Derived()
    {
        m_private = 4 ;
        m_protected = 5 ;
        p_var2 = 6 ;
    }
};

class Lower : private Derived
{
  public:
    Lower()
    {
        p_var1 = 4 ;
        p_var2 = 5 ;
        m_public = 6 ;
    }
};

int main()
{
        Base baseObject ;
        Derived derivedObject ;
        Lower derived1Object ;
        baseObject.m_public = 1;
        baseObject.m_protected = 2 ;
        derivedObject.m_public = 1 ;
        derived1Object.m_public = 1 ;
        derived1Object.p_var3 = 3 ;
}


















File: ex2_s.cpp