Advertisement

help protected member

Started by November 30, 2000 02:53 AM
1 comment, last by haigu 24 years, 1 month ago
hi, i have problem with protected members, for example: class A { protected: int var; }; class B : public A { void function(A *a) { this->var = 0;// correct a->var = 0;// WRONG!!! } } Why can''t child class access the protected member in the parent class, if it''s not his own parent? How can I get this code work, without using public member variable or functions?
Ò»½«¹¦³ÉÍò¹Ç¿Ý
well, you can''t ...
the purpose of protected members is to be accessed by children not by other members of the family, like cousins etc ))

so you''d better make a int A::Getvar() and a int A::Setvar() methods to do what you wanna do ...
Advertisement
quote:
Why can''t child class access the protected member in the parent class, if it''s not his own parent?


It might not be the parent of a ''B'', it could really be a ''C'', e.g.

B* pB = new B;B->(pC); 


The class ''B'' shouldn''t be able to change a C just because it''s a subclass of ''A''. It only has access to the private and protected parts of other B''s. So either change your code to accept a B or use some other way to access the data.

You can break the type checking by forcing a cast inside the B function, but if you start doing stuff like you might as well not be using C++.

This topic is closed to new replies.

Advertisement