Re: @protected variable access
Re: @protected variable access
- Subject: Re: @protected variable access
- From: Ondra Cada <email@hidden>
- Date: Sun, 12 Sep 2004 11:56:50 +0200
Tim,
On 11.9.2004, at 22:30, Tim Hart wrote:
@interface Foo :NSObject { @protected int i; } @end
@interface Bar : Foo
-(id) initWithFoo:(Foo*)foo;
@end
So we have Bar as a subclass of Foo, but also initializable with an
instance of Foo - a quasi-copy initializer.
I was under the impression that initWithFoo could legally do the
following:
@implementation Bar
-(id) initWithFo:(Foo*)foo{
i = foo->i;//legal access to a protected member.
}
@end
Of course it is *not* legal, neither would it be even without
subclassing in a Foo method. You are accessing the property i from the
*outside* here: the property you are trying to access is not part of
self! To be allowed to do that, it would have to be declared @public.
What you really want to is to use a proper encapsulation through an
accessor
@implementation Foo
-(int)i;
-(void)setI:(int)i;
@end
@implementation Bar
-initWithFoo:(Foo*)foo {
if ((self=[super init]))
[self setI:[foo i]];
return self;
}
@end
Note that it is very right to do so; if you did that the Java/C++ way,
you'd be hang dry as soon as there is a subclass which reimplements the
foo's notion of 'i' in its own way. Always use well-defined set of
accessors (or KVC, which would automatically switch to them if and when
needed).
(Just for completeness: yup, there are very rare cases when the
accessors might be unacceptable due to the application speed: nearly
always it means you should re-factor your code :) And yup, it does mean
@protected is not really useable in 99.99% of situations and we should
use @private instead. And that means GCC/ObjC, unlike Java/C++, does it
almost right: completely right it would be if @private were the
default.)
---
Ondra Čada
OCSoftware: email@hidden http://www.ocs.cz
private email@hidden http://www.ocs.cz/oc
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden