Constructors in Objective-C
Last Updated :
12 Mar, 2023
Constructor is basically a function or method that is called automatically at the time of object creation of a class. constructor method has the same name as that of the class. It is basically used to initialize the data members of the new objects generally. It constructs or creates a new value for the data members during object creation based on the value, if given, so that is why we call it a constructor it assigns a new default value to the object so that these values can be used for further uses. the constructor does not have any return type, which means it cannot return any value after performing an operation on data members of that class; it will only return the changes to the self-data members or save the changes done in its data members with the help of constructors.
Constructors always have the same name as that class. and its prototype is first declared in an interface of class (means in the declaration of class) and its implementation part is done in the implementation of class where the definition or body of all the member functions is written so that it can perform operation whenever an object is allocated.
The syntax for defining the constructor:
-(id)init // there will be separate function prototype which is used to create constructor, but the basic one is this
{
// body;
}
Now let us understand with the help of an example how a constructor is created and how it is called and how it performs some operations:-
ObjectiveC
#import <Foundation/Foundation.h>
@interface Constructor : NSObject
-( id )init;
@end
@implementation Constructor
-( id )init
{
NSLog ( @"constructor is called " );
return self ;
}
@end
int main ( int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[ NSAutoreleasePool alloc] init];
[[Constructor alloc] init];
[pool drain];
return 0;
}
|
Output:-
Output
Types of Constructors
There are a total of three types of constructors in Objective C:
- Default constructor
- Parameterized constructor(custom initializer)
- Copy constructor(clone method)
Default constructor
A default constructor is basically used to initialize the default values to all its data members. This will get executed at the time of object creation of class and perform all operations present in this function.
In this type of default constructor it does not take any argument, it self initializes the value to the data members of the class. In this method, we write all the code related to the initial setup of an object. Objective C has a default constructor called init which is present in its root class NSObject. We can override the default constructor.
In Objective C, we initialize the default constructor using the init method only.
-(id)init
and the syntax that default constructor, follow us –
-(id)init
{
if( self = [super init] )
{
// Initialize your data members here
}
return self;
}
Now Let us understand how the default constructor is initialized and how it works and performs its operation;-
Example 1:
ObjectiveC
#import <Foundation/Foundation.h>
@interface Number : NSObject
{
int firstnum;
int secondnum;
}
-( id )init;
-( void )display;
@end
@implementation Number
-( id )init
{
firstnum = 11;
secondnum = 21;
return self ;
}
-( void )display
{
NSLog ( @"First Number is %d and Second Number is %d" ,
firstnum, secondnum);
}
@end
int main ( int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[ NSAutoreleasePool alloc] init];
NSLog ( @"Printing Numbers using default constructor" );
Number *num = [[Number alloc] init];
[num display];
[pool drain];
return 0;
}
|
Output:-
Output
Parameterized constructor
Custom initializers can also be called parameterized constructors. In this type of constructor, we pass the values to the constructor which initializes the values to its self-data members of the class and returns all values to self. This helps to take or initialize the value during object creation. In this parameterized constructor, the user can give his own values during object creation while in the default constructor value is given as default or null. This helps the user to give values according to his use at the time of object allocation and whenever we create a new object we have to pass the values if there is no default constructor otherwise garbage value will be assigned to the data members of the class. The prototype of the parameterized constructor is totally different from the default constructor.
The syntax of a custom initializer or parameterized constructor is as follows –
-(id)initwithDataMember1 : (datatype)value1 DataMember2 : (datatype)value2
{
if( self = [super init] )
{
DataMember1 = value1;
DataMember2 = value2;
}
return self;
}
Now let us understand how the parameterized constructor is initialized and how it works and performs its operation;-
Example 2:
ObjectiveC
#import <Foundation/Foundation.h>
@interface Number : NSObject
{
int firstnum;
int secondnum;
}
-( id )initWithfirstnum : ( int )first
secondnum : ( int )second;
-( void )display;
@end
@implementation Number
-( id )initWithfirstnum : ( int )first secondnum : ( int )second
{
firstnum = first;
secondnum = second;
return self ;
}
-( void )display
{
NSLog ( @"First Number is %d and Second Number is %d" ,
firstnum, secondnum);
}
@end
int main ( int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[ NSAutoreleasePool alloc] init];
NSLog ( @"Printing Numbers using parameterized constructor" );
Number *num = [[Number alloc] initWithfirstnum: 121 secondnum: 343];
[num display];
[pool drain];
return 0;
}
|
Output:-
Output
Copy Constructor
The copy constructor is also called the clone method in objective C and is done with the help of an NSCopying protocol. This copy constructor allows copying the values of all the members to the members of the new object. The function prototype of copy constructor is –
-(id)copyWithZone : (NSZone*)zone
and the Syntax of copy constructor that it follows
-(id)copyWithZone : (NSZone*)zone
{
ClassName *obj = [[[self class] allocWithZone : zone] init];
obj.DataMember1 = self.DataMember1;
obj.DataMember2 = self.DataMember2;
return obj;
}
and syntax to perform copy operations in the main function:-
ClassName *newobject;
newobject = [oldobject copy];
Now let us understand how to copy constructor is initialized and how it works and performs its operation;-
Example 3:
ObjectiveC
#import <Foundation/Foundation.h>
@interface Number : NSObject < NSCopying >
{
int firstnum;
int secondnum;
}
-( void )setfirstnumber : ( int ) first;
-( void )setsecondnumber : ( int ) second;
-( id )copyWithZone : ( NSZone *) zone;
-( void )display;
@end
@implementation Number
-( void )setfirstnumber : ( int ) first;
{
firstnum = first;
}
-( void )setsecondnumber : ( int ) second;
{
secondnum = second;
}
-( id )copyWithZone : ( NSZone *)zone
{
Name *copynumber = [[Number allocWithZone : zone] init];
[copyname setfirstnumber : firstnum];
[copyname setsecondnumber : secondnum];
return copynumber;
}
-( void )display
{
NSLog ( @"First Number is %d and second number is %d" ,
firstnum, secondnum);
}
@end
int main ( int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[ NSAutoreleasePool alloc] init];
Number *number = [[Number alloc] init];
[number setfirstnumber : 121];
[number setsecondnumber : 343];
[number display];
NSLog ( @"After using copy constructor" );
Number *copiednumber;
copiednumber = [number copy ];
[copiednumber display];
[pool drain];
return 0;
}
|
Output:-
Output
Characteristics of the Constructor
- The name of the constructor is the same as the class name.
- Constructors are mostly declared in the public section of the class.
- Constructors do not return values; hence they will update their values to the self-data members.
- A constructor gets called automatically when we create the object of the class.
- Constructors cannot be inherited.
Share your thoughts in the comments
Please Login to comment...