Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

haigu

help protected member

This topic is 6411 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
Advertisement
Guest Anonymous Poster
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 ...

Share this post


Link to post
Share on other sites
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++.

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!