Exforsys
+ Reply to Thread
Results 1 to 2 of 2

inheritance in cpp

This is a discussion on inheritance in cpp within the C and C++ forums, part of the Programming Talk category; whenever i go for any inheritence program even simple single inheritence.i face problem in implementing modifer private ,public and protected. ...

  1. #1
    tufan anand is offline Junior Member Array
    Join Date
    Mar 2011
    Answers
    1

    inheritance in cpp

    whenever i go for any inheritence program even simple single inheritence.i face problem in implementing modifer private ,public and protected. can anyone help me with example from beginning???


  2. #2
    techvinny is offline Moderator Array
    Join Date
    Dec 2010
    Answers
    56
    To put it short and sweet, here's what could be said about access specifiers:
    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.
    The protected access specifier restricts access to member functions of the same class, or those of derived classes.

    Simple example:
    Code:
    class ClassA
    {
    public:
        int m_nPublic; // can be accessed by anybody
    private:
        int m_nPrivate; // can only be accessed by ClassA member functions (but not ClassB classes)
    protected:
        int m_nProtected; // can be accessed by ClassA member functions, or ClassB classes.
    };
    
    class ClassB: public ClassA
    {
    public:
        ClassB()
        {
            // ClassB's access to ClassA members is not influenced by the type of inheritance used,
            // so the following is always true:
    
            m_nPublic = 1; // allowed: can access public ClassA members from ClassB class
            m_nPrivate = 2; // not allowed: can not access private ClassA members from ClassB class
            m_nProtected = 3; // allowed: can access protected ClassA members from ClassB class
        }
    };
    
    int main()
    {
        ClassA cClassA;
        cClassA.m_nPublic = 1; // allowed: can access public members from outside class
        cClassA.m_nPrivate = 2; // not allowed: can not access private members from outside class
        cClassA.m_nProtected = 3; // not allowed: can not access protected members from outside class
    }
    However, you need to also look into the method of inheritance which could change the access of the members.


Latest Article

Network Security Risk Assessment and Measurement

Read More...