![]() |
Protected member inaccessible from derived class - why
Hi all,
Quick question: why doesn't this code compile: class Base { protected: int a; }; class Derived: public Base { public: void test(Base* b) { b->a = 5; } }; int main() { Derived d; Derived d1; d.test(&d1); } The error is that Base::a is protected in the test() method of Derived Thanks in advance Best regards Alex |
Re: Protected member inaccessible from derived class - why
On 11/21/2011 6:10 AM, avasilev wrote:
> Quick question: why doesn't this code compile: > > class Base > { > protected: > int a; > }; > > class Derived: public Base > { > public: > void test(Base* b) > { > b->a = 5; > } > }; > > int main() > { > Derived d; > Derived d1; > d.test(&d1); > } > The error is that Base::a is protected in the test() method of Derived The access to protected members is allowed only for the '*this' object, and not for any other object. IOW, in 'Derived::test' you should be able to access 'this->a', but not 'anyotherBase.a'. That's just the rule of the language. V -- I do not respond to top-posted replies, please don't ask |
Re: Protected member inaccessible from derived class - why
On Nov 21, 2:51*pm, Victor Bazarov <v.baza...@comcast.invalid> wrote:
> On 11/21/2011 6:10 AM, avasilev wrote: > > > > > > > > > > > Quick question: why doesn't this code compile: > > > class Base > > { > > protected: > > * int a; > > }; > > > class Derived: public Base > > { > > public: > > * *void test(Base* b) > > * *{ > > * * *b->a = 5; > > * *} > > }; > > > int main() > > { > > * *Derived d; > > * *Derived d1; > > * *d.test(&d1); > > } > > The error is that Base::a is protected in the test() method of Derived > > The access to protected members is allowed only for the '*this' object, > and not for any other object. *IOW, in 'Derived::test' you should be > able to access 'this->a', but not 'anyotherBase.a'. *That's just the > rule of the language. > > V > -- > I do not respond to top-posted replies, please don't ask Thanks for the response, Victor I thought about this, but I think I remember having written operator methods, that contain something like: MyClass& operator=(MyClass& other) { mMember = other.mMember; ... } where mMember was internal protected stuff. IS there any exception for operators, or I am just mistaken? Thanks |
Re: Protected member inaccessible from derived class - why
On 21.11.2011 14:10, avasilev wrote:
>>> void test(Base* b) > > MyClass& operator=(MyClass& other) > { > mMember = other.mMember; > ... > } > > where mMember was internal protected stuff. IS there any exception > for operators, or I am just mistaken? Can you see any obvious difference above? Cheers & hth., - Alf |
| All times are GMT. The time now is 01:52 AM. |
Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.