Timeline for Derived class cannot access the protected member of the base class
Current License: CC BY-SA 4.0
8 events
when toggle format | what | by | license | comment | |
---|---|---|---|---|---|
Apr 23, 2020 at 15:32 | comment | added | Chris Uzdavinis | @Rick Protected allows access to members (and friends) of the class that declares it, and also to its derived classes. What is NOT allowed is if X is a base with a protected member, and two classes A and B both derive from X. A can see protected member of X only when looking at classes of type A (since it is its own data), but not X's protected members in class B, and vice versa. Given a pointer to base, you don't know if it actually points to A or B, and so to disallow A from seeing B's protected data (and vice versa) it's just not allowed. | |
Apr 22, 2020 at 7:51 | comment | added | Rick |
@ChrisUzdavinis I've been thinking this for a while, about why a derived class member or friend may access the protected members of the base class only through a derived object. And I don't agree with your example. I think the point is, setting protected in a class means user could not have access to it from anywhere outside the class itself, even if from derived class. Check this answer
|
|
Aug 13, 2018 at 15:09 | comment | added | songyuanyao |
@user463035818 Yes. For this case &(derived::x) is same as &(x) and &x .
|
|
Aug 13, 2018 at 15:03 | comment | added | 463035818_is_not_an_ai |
there seems to be a difference between &(foo::x) and &foo::x i wasnt aware of (first is a int* , second is a pointer to int member)
|
|
Aug 13, 2018 at 14:57 | comment | added | Chris Uzdavinis | The reason for this is that a derived class is only allowed to access the base protected members for its own type. Imagine a Shape base class with protected members. If Square inherits from it, we would not want Square to access the protected members of a Circle. (Point being, just because X inherits from Base doesn't mean X should have access to all Base protected members, only from those that are actually in use by objects of type X.) The base::qualification no longer is in the context of a derived class, and so the protected access prevents it. | |
Aug 13, 2018 at 14:55 | comment | added | songyuanyao |
@user463035818 g = &x; ? No. &x is with type int* , which can't be assigned to pointer to member. LIVE
|
|
Aug 13, 2018 at 14:43 | vote | accept | Novice_Developer | ||
Aug 13, 2018 at 14:34 | history | answered | songyuanyao | CC BY-SA 4.0 |