0

Protected members in inheritance

Correct me if I am wrong..The definition of protected members goes like “A protected member is accessible by its own class and any class ‘immediately' derived from it"(as per balagurusamy's book).. So program like this is valid: class A{ protected: int a; }; class B : public A { public : void get() { cin>>a; cout<<a<<endl; } }; int main() { B b; b.get(); return 0; } But this program is also not giving any error and is running perfectly.. class A{ protected: int a; }; class B : public A { public : void get() { cin>>a; cout<<a<<endl; } }; class C : public A { public: void gets() { cin>>a; cout<<a; } }; int main() { B b; C c; b.get(); c.gets(); return 0; } So as per the definition protected member 'a' of class A can only be accessed by Class A and B..So this prpgram should give error but it isn't..WHY?? See comment section..

23rd Sep 2019, 1:15 PM
Alaska
Alaska - avatar
4 ответов
0
~ swim ~ Yeah I know ..But Most of the books have written that they are only accessible by the class immediately derived from base class..So are they wrong?
23rd Sep 2019, 1:37 PM
Alaska
Alaska - avatar
- 1
And if this program is valid and should not give any error so can you explain what is difference between public members and protected members? As both can be accessed by derived classes so whats the use of protected members if we can access it in all derived classes???
23rd Sep 2019, 1:17 PM
Alaska
Alaska - avatar