开发者

Need Help in Inheritance

开发者 https://www.devze.com 2023-02-26 21:37 出处:网络
I have read this question, I still have doubts in my concepts of inheritance.I have tried to solve a homework assignment but I think that I still d开发者_如何学JAVAon\'t get the access levels. I have

I have read this question, I still have doubts in my concepts of inheritance.I have tried to solve a homework assignment but I think that I still d开发者_如何学JAVAon't get the access levels. I have following questions in my mind,

Is protected and public access specifier same? (I don't find a difference)

My assignment is attached below,please help me out if it is incorrect.

Need Help in Inheritance

Need Help in Inheritance


The difference is that protected members are only visible/accessible to child classes.

class A {
public:
  int a; // anything can access this member.
private:
  int b; // only A can access this member.
protected:
  int c; // A and every other class that inherits this member can access it.
};


No, they're not the same.

public means that any other class can access the member.

private means it's only accessible by it's own class

protected means it's accessible by the own class, and all classes derivated from the class

Example:

class 1 {
    public void do1() { }
    private void do3() { }
    protected void do2 { }

    1()
    {
        public void do1() { } // ok
        private void do2() { } // ok
        protected void do3 { } // ok
    }
}

class 2 {
    2()
    {
        1.do1() { } // ok
        1.do2() { } // ERROR
        1.do3 { } // ERROR
    }
}

class 3 inherits class 1 {
    3()
    {
        do1() { } // ok
        do2() { } // ERROR
        do3 { } // ok = this class can access the the protected member of it's base class
    }
}


You seem to have forgotten the simplest and the most important aspect: Accessibility of members from an unrelated class / in a freestanding (non-member) function. Public members can be accessed from outside the class and the class hierarchy, private and protected ones cannot.

If you mean public vs protected inheritance, well, the answer is there on your charts.


Protected members of a Base class can only be accessed by the Base class and class derived from base class.

**Private Members** can be only accesed by its own class and cannot be accesed by the derived class.

**Public members** can be accessed by any class including the derived class.

Please check this question

0

精彩评论

暂无评论...
验证码 换一张
取 消