Open In App

Constructors in Objective-C

Last Updated : 12 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




// Header File
#import <Foundation/Foundation.h>
  
// Interface declaration
@interface Constructor : NSObject
-(id)init;
@end
  
// Interface implementation
@implementation Constructor
-(id)init
{
    NSLog(@"constructor is called ");
    return self;
}
@end
  
// Main Function
int main (int argc, const char * argv[])        
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
     
   // Object creation of interface and 
   // calling the default constructor
   [[Constructor alloc] init];
   [pool drain];
   return 0;
}


Output:-

Output

Output

Types of Constructors

There are a total of three types of constructors in Objective C:

  1. Default constructor
  2. Parameterized constructor(custom initializer)
  3. 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




// Header File
#import <Foundation/Foundation.h>
  
// Interface declaration
@interface Number : NSObject
{
    int firstnum;
    int secondnum;
}
-(id)init;
-(void)display;
@end
  
// Interface implementation
@implementation Number
  
// Default constructor returning self value
-(id)init
{
    firstnum = 11;
    secondnum = 21;
    return self;
}
  
// Display function to print the values
-(void)display
{
    NSLog(@"First Number is %d and Second Number is %d"
            firstnum, secondnum);
}
@end
  
// Main Function
int main (int argc, const char * argv[])     
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
     
   // Output statement
   NSLog(@"Printing Numbers using default constructor");
     
   // Object Creation
   Number *num = [[Number alloc] init];
    
   // calling display function using num object
   [num display];
     
   [pool drain];
   return 0;
}


Output:-

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




// Header File
#import <Foundation/Foundation.h>                  
  
//  interface declaration
@interface Number : NSObject
{
    int firstnum;
    int secondnum;
}
  
// Declaration of Parameterized constructor
-(id)initWithfirstnum : (int)first
secondnum : (int)second;
-(void)display;
@end
  
// Interface implementation
@implementation Number
  
// Definition of parameterized constructor
-(id)initWithfirstnum : (int)first secondnum : (int)second
{
    firstnum = first;
    secondnum = second;
    return self;
}
  
// Display function to print the values
-(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");
     
   //  Object creation and initializing 
   // the constructor during object creation
   Number *num = [[Number alloc] initWithfirstnum: 121 secondnum: 343];     
     
   // calling display function to print
   // values with the help of object
   [num display];
   [pool drain];
   return 0;
}


Output:-

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




// Header File
#import <Foundation/Foundation.h>
  
// Interface Declaration
@interface Number : NSObject <NSCopying>
{
    int firstnum;
    int secondnum;
}
-(void)setfirstnumber : (int) first;
-(void)setsecondnumber : (int) second;
-(id)copyWithZone : (NSZone *) zone;
-(void)display;
@end
  
// Interface Implementation
@implementation Number
  
// Function to initialize the values
-(void)setfirstnumber : (int) first;
{
    firstnum = first;
}
  
// Function to initialize the values
-(void)setsecondnumber : (int) second;
{
    secondnum = second;
}
  
// Copy Constructor to copy all the values 
// to new object with the help of NSZone
-(id)copyWithZone : (NSZone *)zone
{
    Name *copynumber = [[Number allocWithZone : zone] init];
    [copyname setfirstnumber : firstnum];
    [copyname setsecondnumber : secondnum];
    return copynumber;
}
  
// Display Function to print the values
-(void)display
{
    NSLog(@"First Number is %d and second number is %d"
            firstnum, secondnum);
}
@end
  
// Main Function
int main (int argc, const char * argv[])
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
     
   // Object creation
   Number *number = [[Number alloc] init];
    
   // initializing the values 
   [number setfirstnumber : 121];
   [number setsecondnumber : 343];
    
   // Display the values
   [number display];
     
   NSLog(@"After using copy constructor");
     
   // creating new object
   Number *copiednumber;
    
   // copying all the values to the new object
   // with the help of old object
   copiednumber = [number copy];
     
   // display the values of new object
   [copiednumber display];
     
   [pool drain];
   return 0;
}


Output:-

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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads