Objective C Constructors

Objective-C enables user to define constructor with the help of self and super keywords.

Objective C Constructors

Objective C Constructors

     

Objective-C enables user to define constructor with the help of self and super keywords. Like java Objective-C has parent class and programmer can access its constructor by statement [super init], this statement returns a instance of parent class which we assign to the 'self' keyword, actually 'self' plays same role as this keyword in C++ and Java. The default constructor is -(id) init statement if(self) is used to check the condition self != nil to confirm that parent class returned a new object successfully.

Example:

MyClass.h
#import<Foundation/NSObject.h>
@interface MyClass:NSObject{
int a;
int b;
}
// declare constructor
-(MyClass*) set:(int) a andb:(int) b;
-(void) sum;
@end

MyClass.m

#import<stdio.h>
#import"MyClass.h"
@implementation MyClass
// define constructor
-(MyClass*) set:(int) x andb:(int) y {
  self = [super init];
  if(self) {
    a=x;
    b=y;
    return self;
}
}
-(void) sum {
printf("Sum is : %d",a+b);
}
@end

MyClassMain.m

#import<stdio.h>
#import"MyClass.m"
int main(){

// use constructor
MyClass *class = [[MyClass alloc] set : 10 andb : 12];
[class sum];
[class release];
return ;
}

Output:

Sum is : 22