objlv
objlv

Reputation: 35

Access private instance variable of parent class

I can't figure out why class B can access class A private instance variable. Here is my code

A.h

#import <Foundation/Foundation.h>

@interface A : NSObject 
{

@private
    int x;
}

@property int x;

-(void)printX;
@end

A.m

#import "A.h"

@implementation A
@synthesize x;

-(void)printX
{
    NSLog(@"%i", x);
}

@end

B.h

 #import "A.h"

    @interface B : A 
    {

    }

    @end

main.m

    B *tr = [[B alloc] init];
    tr.x = 10; 
    [tr printX];

Here I can access instance variable of A class x despite it is declarated as private ?

Upvotes: 0

Views: 688

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

You are not accessing the private variable there, at least not directly: you are accessing a public property, which has legitimate access to the private ivar.

Your code is equivalent to this:

B *tr = [[B alloc] init];
[tr setX:10]; 
[tr printX];

The @synthesize statement created the getter and the setter methods for you. If you want only a getter to be available, mark your property readonly, and do all writings through an ivar in the A class.

Upvotes: 2

Shubhank
Shubhank

Reputation: 21805

In your implementation file do this on the top..

@interface A : NSObject 
{

@private
    int x;
}
@property int x;
@end

this way x will be private since it is in the implementation file. not the interface section...all classes import the interface section of A ..so it's variable are accessible to its subclasses.

Upvotes: -1

Related Questions