Allan W wrote:[color=blue]
> Chetan Raj wrote: (edited for brevity)[/color]
[color=blue][color=green]
>>#include <iostream>
>>using namespace std;[/color][/color]
[color=blue][color=green]
>>class A {
>>protected:
>> A() : x(5) {}
>> int GiveX() { return x; }
>> int x ;
>>};[/color][/color]
[color=blue][color=green]
>>class B : public A {
>>public:
>> B() {[/color][/color]
[color=blue]
> // This line gets error "cannot access protected member"[/color]
[color=blue][color=green]
>> A* p = new A();[/color][/color]
[color=blue]
> // But this line does not:[/color]
[color=blue][color=green]
>> cout<<"I am B with x = "<<GiveX()<<endl;
>> }
>>};[/color][/color]
[color=blue]
> I was certain this was one of Marshal Cline's FAQs, but I
> couldn't find it when I searched.[/color]
[color=blue]
> Chetan, this confused me too when I first encountered it. The
> answer is that just because B inherits from A does not mean
> that it has friend-type access to all of the protected
> members. It only has access to the protected members of the
> base object -- the A that's part of the B.[/color]
Almost. You need to replace the 'the's with 'a's in the last
sentence. A derived class B can only access the protected
members of a base A in objects whose actual type is a B (or
derived from B). In his example, for example :
B* pB ;
pB->GiveX() ; // Legal.
A* pA ;
pA->GiveX() ; // Illegal.
--
James Kanze mailto:
james.kanze@free.fr
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 pl. Pierre Sémard, 78210 St.-Cyr-l'École, France +33 (0)1 30 23 00 34
[ See
http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]