C++Talk.NET Forum Index C++Talk.NET
C++ language newsgroups
 
Archives   FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

Protected Member Access

 
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ Language (Moderated)
View previous topic :: View next topic  
Author Message
Andy Tompkins
Guest





PostPosted: Sat Jul 17, 2004 10:05 am    Post subject: Protected Member Access Reply with quote



I am having trouble understanding why line B will not compile. I understand
why line A and line C compiles since they have access to the i member. But
since D is derived from Base should it not have access to another Base
object's i member as well as access to it's own Base's i member?

class Base {
public:
Base() {}
virtual ~Base() {}
protected:
int i;
};
class D : public Base {
public:
void foo() {
int i1 = i; // line A

Base *b = new D();
int i2 = b->i; // line B, compile error, 'Base::i' :
cannot access protected member declared in class 'Base'

if (D *d = dynamic_cast<D*>(b)) {
int i3 = d->i; // line C
}
}
};

Thanks,
Andy.


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
Back to top
Francis Glassborow
Guest





PostPosted: Sat Jul 17, 2004 5:13 pm    Post subject: Re: Protected Member Access Reply with quote



In article <m%RJc.47549$Rf.45684@edtnps84>, Andy Tompkins
<atompkins (AT) georef (DOT) com.invalid> writes
Quote:
I am having trouble understanding why line B will not compile. I understand
why line A and line C compiles since they have access to the i member. But
since D is derived from Base should it not have access to another Base
object's i member as well as access to it's own Base's i member?

No, that is not the meaning of protected. protected means that a derived
object has access to the data of its own base subobject, nothing more.
It does not grant access to the data of all instances of the base.


--
Francis Glassborow ACCU
Author of 'You Can Do It!' see http://www.spellen.org/youcandoit
For project ideas and contributions: http://www.spellen.org/youcandoit/projects


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Back to top
Display posts from previous:   
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ Language (Moderated) All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2006 phpBB Group
SEO toolkit © 2004-2006 webmedic.