Constructor

class के सामान नाम वाले  member function को construction कहा जाता है | 

और इसका उसे एक सामान initialize value के साथ उस class type के object को  initialize करने के लिए किया जाता है | 

  • class का special member function होता है |  
  • जिसका नाम class के नाम जैसा होता है | 
  • इसे बिना किसी return type declared किया जा सकता है | 

Constructor की आवश्यकता :-

class के लिए constructor इसलिए आवश्यक है ,क्योकि जैसे ही कोई object  बनता है ,तो compiler अपने आप इसे initilize कर देता है | 

जब भी कोई program उस class  के object को निर्मित करता है ,तब  एक class constructor यदि difine किया गया है तो call किया जा सकता है, इसलिए ऐसी स्थिति में हमें की constructor आवश्यकता होती है | 

Types of Constructor :-

  • Default constructor
  • parameterized constructor
  • copy constructor

Default constructor :-

यह constructor का नाम class के नाम के समान होता है।
जब object बनता है तब यह अपने आप call होता है। इसमें कोई argument pass नहीं किया जाता |

syntax 

   class A

   { 

            A()

     {

      }

   void input()

      {

       }

   };

program:-

#include <iostream.h>

class A


{


Public:


int a, b;

 

A()  // default constructor


{


a = 10;


b = 20;


        }

     

void input()


{


cout << a << b;


}

void main()


{


A a1;


  a1.input();


}

parameterized constructor :-

इस constructor का नाम class से नाम के समान होता है। तथा स्वतः call हो जाता है।
किंतु इसमें argument pass किया जाता है।

NOTE:- argument के रूप में value और variable pass किया जाता है |

 

program:-


class A


{


public:


int a, b;

 

A()


{


a = 10;


b = 20;


}

A(int x, int y)


{


a = x;


b = y;


}

 

void output()


{


cout << a << ” ” << b;


}

void main()


{


A a1(10, 20);


a1.output();


}

 

 

Output 

10 20

Copy Constructor ::-

इस constructor का नाम class के नाम के समान होता है।
तथा इसमें argument के रूप में object पास किया जाता है।

 

program:-

class A

{

public:

int a, b;

A()

{

a = 10;

b = 20;

}

A(int x, int y)

{

a = x;

b = y;

}

void output()

{

cout << a << ” ” << b;

}

void main()

{

A a1(10, 20);

a1.output();

}

Output 

10 20

Scroll to Top