Home Iphone Objectivec Objective C Constructors



Objective C Constructors
Posted on: May 24, 2009 at 12:00 AM
Objective-C enables user to define constructor with the help of self and super keywords.

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

Related Tags for Objective C Constructors:
javac++cobjective-cclassconstructorobjectstructwordconstkeystatereturnoleinstancethisparentprogrammerlikekeywordelfprogramstatementtoiniramselfssiesignsupersuperitcanliinitpeceinroleasstamntplaypartrcajclesemallmeobjobjectiveprotorsamewhichsurnsuctoressatkishallivlfactualandarstatactccconsstrsavassamssamrdrenthavstaccessctojeplprndonogrolo


More Tutorials from this section

Ask Questions?    Discuss: Objective C Constructors   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.