Pages

Monday 8 November 2021

Constructors & Destructors in c++

 ConstructorsA Constructor is a special member function, which is used to initialize the objects of its class. The Constructor is invoked whenever an object of its associated class is created. The constructor constructs the value of data members of the class.

Syntax:

          Class class_name
          {
               private:
                 data members;
               public:
                 class_name();
          };
          class_name::class_name()
          {
               ----------------
               ----------------
          }

 Example:

          Class sample
          {
               public:
                     sample();
          };
          sample::sample()
          {
               cout<<”constructor Demo”;
          }

 Characteristics of a constructor:- 

  • They should be declared in the public section.
  • They are invoked automatically when the objects are created.
  • They do not have return type not even void.
  • They cannot be inherited, though a derived class can call the base class constructor.
  • They can have default arguments
  • The compiler calls constructor implicitly as soon as an object of its type is created.
  • Constructors can be overloaded.
  • The constructor name is same as class name.

Types of Constructors

  1. Default Constructor
  2. Parameterized Constructor
  3. Constructor Overloading
  4. Constructor with default arguments
  5. Copy Constructor
  6. Dynamic constructor

Default Constructor :

A constructor that accepts no parameters is called the default constructor. 

Example: 

//default constructor

#include<iostream.h>
#include<conio.h>
class sample
{
     int a;
     public:
     sample()
     {
          a=10;
          cout<<"constructor called"<<endl;
          cout<<"value="<<a;
     }
};
void main()
{
     clrscr();
     sample s;  //constructor called
     getch();
}
Output: 
constructor called
value=10

Parameterized Constructor 

It is possible to pass arguments to constructor functions. These arguments help to initialize an object when it is created. The constructor that takes arguments are called as parameterized constructors. We must pass the initial values as arguments to the constructor function when an object is declared. This can be done in 2 ways.

 1.By calling constructor explicitly

 Ex: integer int1=integer(0,100);

 2.By calling constructor implicitly

 Ex: integer int1(0,100); 

Example: 

//parameterized constructor using implicitly

#include<iostream.h>
#include<conio.h>
class paracons
{
     int a,b;
     public:
     paracons(int x,int y)
     {
          a=x;
          b=y;
     }
     void show()
     {
          cout<<"A="<<a<<endl;
          cout<<"B="<<b<<endl;
     }
};
void main()
{
     clrscr();
     paracons pc(5,15);
     pc.show();
     getch();
}

Output:
A=5
B=15 

//parameterized constructor using explicitly

#include<iostream.h>
#include<conio.h>
class paracons
{
     int a,b;
     public:
     paracons(int x,int y)
     {
          a=x;
          b=y;
     }
     void show()
     {
          cout<<"A="<<a<<endl;
          cout<<"B="<<b<<endl;
     }
};
void main()
{
     clrscr();
     paracons pc = paracons(25,15);
     pc.show();
     getch();
}

Output:
A=25
B=15 

Constructor with default arguments 

          We can declare constructor with default arguments. When the constructor is declared with some default arguments while calling the constructor less no of arguments can be passed. 

Example: 

//constructor with default arguments

#include<iostream.h>

#include<conio.h>

#include<string.h>

class defcons

{

int rank;

char team[20];

public:

defcons();  //default constructor

defcons(char [], int x=1);       //with default arguments

void show();

};

defcons::defcons()

{

rank=-1;

strcpy(team,"null");

}

defcons::defcons(char y[],int x)

{

rank=x;

strcpy(team,y);

}

void defcons::show()

{

cout<<team<<endl<<rank<<endl;

}

void main()

{

clrscr();

defcons dc1;

defcons dc2("India",2);

defcons dc3("Australia"); //calls constructor with default arguments

dc1.show();

dc2.show();

dc3.show();

getch();

}

Output:

null

-1

India

2

Australia

1 

Constructor Overloading 

When more than one constructor is having in a class then it is called as constructor overloading. 

Example: 

//constructor overloading

#include<iostream.h>

#include<conio.h>

class sample

{

char a;

public:

sample();

sample(char);

void print();

};

sample::sample()

{

cout<<"0-args constructor called"<<endl;

a='i';

}

sample::sample(char x)

{

cout<<"1-args constructor called"<<endl;

a=x;

}

void sample::print()

{

cout<<a<<"\t";

}

void main()

{

clrscr();

sample s1('h');

sample s2;

s1.print();

s2.print();

getch();

}

Output:

1-args constructor called

0-args constructor called

h       i 

Copy Constructor 

A constructor is used to create a new instance from existing one. A copy constructor also always takes argument of class type that to of reference type. Copy constructor is always used when the compiler has to create a temporary object of a class object. The compiler calls copy constructor implicitly as soon as an object is initialized to another object of its type. 

Example: 

//copy constructor

#include<iostream.h>

#include<conio.h>

#include<string.h>

class copy

{

int data;

char info[20];

float value;

public:

copy();

copy(int,char [],float);

copy(copy &);

void show();

};

copy::copy()

{

data=-1;

strcpy(info,"null");

value=0.00;

}

copy::copy(int x,char y[],float z)

{

data=x;

strcpy(info,y);

value=z;

}

copy ::copy(copy &c)

{

c.data+=2;

data=c.data;

strcpy(info,c.info);

value=c.value;

}

void copy::show()

{

cout<<data<<info<<value<<endl;

}

void main()

{

clrscr();

copy a;

copy b(1,"Jack",9.27);

a.show();

b.show();

copy q(b); //copy constructor called

q.show();

copy x;

x=b;

b.show();

x.show();

copy k(b);

b.show();

x.show();

k.show();

getch();

}

Output:

-1null0

1Jack9.27

3Jack9.27

3Jack9.27

3Jack9.27

5Jack9.27

3Jack9.27

5Jack9.27

Dynamic Constructor 

The constructors are used to allocate the memory dynamically at runtime depending upon the need of object without preallocating. 

Example: 

//dynamic constructor

#include<iostream.h>

#include<conio.h>

#include<string.h>

class dynamic

{

char *st;

int len;

public:

dynamic();

dynamic(char []);

void merge(dynamic,dynamic);

void show();

};

dynamic::dynamic()

{

len=1;

st=new char[len];

st=" ";

st='\0';

}

dynamic::dynamic(char x[])

{

len=strlen(x);

st=new char[len+1];

strcpy(st,x);

}

void dynamic::merge(dynamic d,dynamic e)

{

len=d.len+e.len;

st=new char[len+1];

strcpy(st,d.st);

cout<<st;

strcpy(st,e.st);

}

void dynamic::show()

{

cout<<st<<"->"<<len<<endl;

}

void main()

{

clrscr();

dynamic d;

dynamic e("hai");

dynamic f("student");

dynamic k;

d.show();

e.show();

f.show();

k.merge(e,f);

k.show();

getch();

}

Output:

->1

hai->3

student->7

haistudent->10 

Destructors 

A destructor is used to destroy the objects that have been created by a constructor.

  • A destructor is a special member function whose name is same as that of its class name except that it is preceded by a tidle ( ~ ) symbol.
  • A destructor is used to deallocate the memory
  • It has no return type.
  • Destructors cannot be overloaded
  • Compiler calls destructor implicitly just before an object goes out of its scope. 

Example: 

//destructors

#include<iostream.h>
#include<conio.h>
class dest
{
public:
dest();
~dest();
};
dest::dest()
{
cout<<"constructor called"<<endl;
}
dest::~dest()
{
cout<<"destructor called";
}
void main()
{
clrscr();
dest d;
getch();
} 

Output:
constructor called

Difference between constructors and destructors

 

Constructors

Destructors

Constructors will initialize the objects

Destructors will deinitialize the objects

A class can have multiple constructors

A class can have only one destructor

It can take arguments

It cannot take arguments

It is same as a classname

It is same as a classname but preceded by a tidle.

Program on Constructor and Destructor

#include<iostream.h>
#include<conio.h>
class sample
{
 int a,b;
 public:
 sample()  //constructor
 {
 a=10;
 b=20;
 }
 ~sample() //destructor
 {
 cout<<"a value is "<<a<<endl;
 cout<<"b value is "<<b<<endl;
 getch();
}
};

void main()
{
 clrscr();
 sample sa; //object
} 

output: a value is 10
              b value is 20 

No comments:

Post a Comment

Constructors & Destructors in c++

  Constructors :  A Constructor is a special member function, which is used to initialize the objects of its class. The Constructor is invok...