0

I have worked on c++, there we used initializer list like below to initialize the constructor of base class.

Derived::Derived(int x):Base(x) { 
    cout << "B's Constructor called";
} 

How to acheive the same action in objective C. How to pass value to base (super) class while initlizing. Is it possible?

thanx.

Newbee
  • 3,231
  • 7
  • 42
  • 74

4 Answers4

2

Here we use super to call the Base Class Constructor. For example: Lets say we have a base class, and has this initiator method

// Base .h
- (id)initWithName:(NSString *)name;
@property (strong, nonatomic) NSString *name;

// Base.m
- (id)initWithName:(NSString *)name
 {
   self = [super init];
   if(self){
     self.name = name;
   }
  return self
 }

 // Derived.h
- (id)initWithName:(NSString *)name;

// Derived.m
- (id)initWithName:(NSString *)name
 {
   self = [super initWithName:name];
    return self;
 }

// This is how we can create an object of Derived class
Derived *derived = [[Derived alloc]initWithName:@"foo"];
Puneet Sharma
  • 9,369
  • 1
  • 27
  • 33
0
- (instancetype)init {
    if (self = [super init]) {
       // your code here
    }
    return self;
}
Nate Symer
  • 2,185
  • 1
  • 20
  • 27
Krishna Kumar
  • 1,652
  • 9
  • 17
0

In Objective-C, there is no constructor, the subclass needs to call parent's class's init method explicitly. like [super init];

Here is a good article to describe the initialiser of Objective C objects. Object Initialization

Jake Lin
  • 11,146
  • 6
  • 29
  • 40
0

We use [super init]; to initialize all your super classes. It does what you require.

iOS
  • 3,526
  • 3
  • 37
  • 82