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 

Program to illustrate Queue using Linked list in c++

   /* Program on Queue using linked list*/

#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include <process.h>
#include<mem.h>
struct node
{
int info;
struct node *link;
};
struct node *front,*rear,*tmp,*q;

class rkslqueue
{
public:
void insert(void);
void del(void);
void display(void);
};

void rkslqueue::insert()
{
int added_item;
struct node* newnode = new node;
tmp=newnode;
cout<<"Add the new value to queue : ";
cin>>added_item;
tmp->info=added_item;
tmp->link=NULL;
if(front==NULL)
 front=tmp;
else
 rear->link=tmp;
   rear=tmp;
}/*End of insert()*/

void rkslqueue::del()
{
if(front == NULL)
cout<<"Queue underflow\n";
else
{       tmp=front;
cout<<"Deleted item is:"<<tmp->info;
front=front->link;
delete(tmp);
}
}/*End of del()*/

void rkslqueue::display()
{
q=front;
if(front == NULL)
{
cout<<"\nQueue is empty\n";
}
else
{
cout<<"\nSingly linked List is: \n";
while(q!=NULL)
{
cout<<"||"<<q<<"----->"<<q->info;
q=q->link;
}
cout<<"|| "<<NULL ;
}
}/*End of display() */

void main()
{
int choice;
rkslqueue sl;
front=NULL;
rear=NULL;
clrscr();
while(1)
{       cout<<"\n MENU \n";
cout<<"1.Insert\n";
cout<<"2.Delete\n";
cout<<"3.Display\n";
cout<<"4.Quit\n";
cout<<"Enter your choice : " ;
cin>>choice;
switch(choice)
{
case 1:
sl.insert();
break;
case 2:
sl.del();
break;
case 3:
sl.display();
break;
case 4:
exit(1);
default :
cout<<"Wrong choice\n";
}/*End of switch */
}/*End of while */
}/*End of main() */

Output:

Program to illustrate Queue using Arrays in c++

  /* queue implementation with class and object using array */

#include<iostream.h>
#include<conio.h>
#include<process.h>
#define max 20

int i,n,qa[max],item,front=-1,rear=-1; /* global declaration */

class rkqueue
{
public:
int add(void); /* create function declaration */
int del(void); /* delete function declaration */
int display(void); /* display function declaration */
};

int rkqueue::add(void) /* implementation function */
  {
    if(rear==n-1)
     {
     cout<<"\n queue overflow";
     return rear;
     }
    else
    {
     if(front==-1)
     {
       front=0;
     }
     rear++;
     cout<<"\n enter item to be added on to the queue:";
     cin>>item;
     qa[rear]=item;
     return rear;
    }
  }

int rkqueue::del(void) /* implementation function */
   {
    if(front==-1 || front>rear)
    {
    cout<<"\n queue underflow ";
    return front;
    }
    else
    {
    cout<<"\n The deleted item from queue is="<<qa[front];
    qa[front]='\0';
    if(front==rear)
     {
      front=-1;
      rear=-1;
     }
    front++;
    return front;
   }
 }

int rkqueue::display()
   {
   if((front<0 && rear<0)||(front>rear))
    {
    cout<<"\n queue is empty";
    }
    else
    {
    cout<<"\nqueue elements are:";
    for(i=0;i<n;i++)
     {
     if(qa[i] == '\0')
      cout<<" \t ";
     else
     cout<<qa[i]<<"  ";
     }
     cout<<"\n Position of front "<<front<<" and rear is "<<rear;
   }
 }

void main()
{
   rkqueue q;
   int choice;
    clrscr();
    cout<<"\nEnter the length of the queue array  :\n";
    cin>>n;
 while(1)
 {
    cout<<"\n  MENU \n";
    cout<<"  1.Add to queue  \n";
    cout<<"  2.Delete from queue \n";
    cout<<"  3.Display   \n";
    cout<<"  4.Quit      \n";
    cout<<"Enter ur choice: ";
    cin>>choice;
    switch(choice)
    {
       case 1: q.add();break;
       case 2: q.del();break;
       case 3: q.display();break;
       case 4: exit(1);break;
       default:cout<<"\n u have entered wrong choice";break;
    } /* end of switch case */
  }/* end of while loop */
}

Output:

/*Queue implementation without class and object using array */
#include<iostream.h>
#include<conio.h>
#include<process.h>
#define max 20
int add(void); /* create function declaration */
int del(void); /* delete function declaration */
int display(void); /* display function declaration */
int i,n,qa[max],item,front=-1,rear=-1; /* global declaration */

void main()
{
   int choice;
    clrscr();
    cout<<"\nEnter the length of the queue array  :\n";
    cin>>n;
 while(1)
 {
    cout<<"\n  MENU \n";
    cout<<"  1.Add to queue  \n";
    cout<<"  2.Delete from queue \n";
    cout<<"  3.Display   \n";
    cout<<"  4.Quit      \n";
    cout<<"Enter ur choice: ";
    cin>>choice;
    switch(choice)
    {
       case 1: add();break;
       case 2: del();break;
       case 3: display();break;
       case 4: exit(1);break;
       default:cout<<"\n u have entered wrong choice";break;
    } /* end of switch case */
  }/* end of while loop */
}

int add(void) /* implementation function */
  {
    if(rear==n-1)
     {
     cout<<"\n queue overflow";
     return rear;
     }
    else
    {
     if(front==-1)
     {
       front=0;
     }
     rear++;
     cout<<"\n enter item to be added on to the queue:";
     cin>>item;
     qa[rear]=item;
     return rear;
    }
  }

int del(void) /* implementation function */
   {
    if(front==-1 || front>rear)
    {
    cout<<"\n queue underflow ";
    return front;
    }
    else
    {
    cout<<"\n The deleted item from queue is="<<qa[front];
    qa[front]='\0';
    if(front==rear)
     {
      front=-1;
      rear=-1;
     }
    front++;
    return front;
   }
 }

int display()
   {
   if((front<0 && rear<0)||(front>rear))
    {
    cout<<"\n queue is empty";
    }
    else
    {
    cout<<"\nqueue elements are:";
    for(i=0;i<n;i++)
     {
     if(qa[i] == '\0')
      cout<<" \t ";
     else
     cout<<qa[i]<<"  ";
     }
     cout<<"\n Position of front "<<front<<" and rear is "<<rear;
   }
 }


ANIMATION VIDEO LINK OF QUEUE :
https://www.youtube.com/watch?v=vPVWuoR43oM

Program to illustrate Merge sort in c++

 Merge sort program with out class and object:

#include<iostream.h>
#include<conio.h>
void merge(int *,int, int , int );
void merge_sort(int *arr, int p, int r)
{
    int q;
    if (p < r)
     {
//divide the array at mid and sort independently using merge sort
q=(p+r)/2;
cout<<"\n\t First and second array elements:";
for (int i = 0; i < r+1; i++)
cout<<arr[i]<<"  ";
merge_sort(arr,p,q);
merge_sort(arr,q+1,r);
//merge or conquer sorted arrays
merge(arr,p,q,r);
cout<<"\n Merged  array elements:";
for (int k = 0; k < r+1; k++)
cout<<arr[k]<<"  ";
    }
}

// Merge sort
void merge(int *arr, int p, int q, int r)
{
    int i, j, k, c[50];
    i = p;
    k = p;
    j = q + 1;
    while (i <= q && j <= r)
{
if (arr[i] < arr[j])
      {
    c[k] = arr[i];
    k++;
    i++;
}
else
     {
    c[k] = arr[j];
    k++;
    j++;
}
}
    while (i <= q)
       {
c[k] = arr[i];
k++;
i++;
       }
    while (j <= r)
  {
c[k] = arr[j];
k++;
j++;
    }
    for (i = p; i < k; i++)
     {
arr[i] = c[i];
    }
}

// read input array and call mergesort
void main()
{
    int myarray[30], num;
    clrscr();
    cout<<"Enter number of elements to be sorted:";
    cin>>num;
    cout<<"Enter "<<num<<" elements to be sorted:";
    for ( int i = 0; i < num; i++)
      cin>>myarray[i];

    merge_sort(myarray, 0, num-1);
    cout<<"\n Sorted array:";
    for (i = 0; i < num; i++)
cout<<myarray[i]<<"  ";
getch();
}

output:


Merge sort program with class and object :
#include<iostream.h>
#include<conio.h>
class mergesort
{
    public:
int i,n;
int arr[10];
    public:
void getarray();
void partition(int * ,int ,int);
void sortit(int *, int , int, int);
void display();
};

// get the array to be sorted from the user
void mergesort::getarray()
{
    cout<<"Enter Array size: ";
    cin>>n;
    cout<<"unsorted array: ";
    for(int i=0;i<n;i++){
cin>>arr[i];
    }
}

// recursively divide the array into sub arrays until all sub
// arrays contain only one element
void mergesort::partition(int *arr, int p, int r)
{
    int q;
    if(p<r)
    {
q=(p+r)/2;
cout<<"\n\tfirst and second array element :";
for(i = 0 ; i <r+1; i++)
 cout<<arr[i]<<" ";
// sort the left sub array
partition(arr,p,q);
// sort the right sub array
partition(arr,q+1,r);
sortit(arr,p,q,r);
       {
cout<<"\nmerged a
rray element :";
for(int k = 0 ; k <r+1; k++ )
cout<<arr[k]<<" ";
       }
    }
  }
void mergesort::sortit(int *arr, int p, int q, int r)
{
    int i,j,k,l,b[20];
    l=p;
    i=p;
    j=q+1;
    while((l<=q)&&(j<=r))
        {
         if(arr[l]<=arr[j])
              {
    b[i]=arr[l];
    l++;
}else{
    b[i]=arr[j];
    j++;
}
i++;
    }
    if(l>q){
for(k=j;k<=r;k++){
    b[i]=arr[k];
    i++;
}
    }
    else
    {
for(k=l;k<=r;k++){
    b[i]=arr[k];
    i++;
}
    }
    for(k=p;k<=r;k++){
arr[k]=b[k];
    }
}
void mergesort::display(){
    cout<<"\n The sorted element :";
    for(int i = 0 ; i < n; i++){
cout<<arr[i]<<" ";
    }
}
void main(){
    clrscr();
    mergesort ms;
    ms.getarray();
    ms.partition(ms.arr,0,ms.n-1);
    ms.sortit(ms.arr,0,ms.n,ms.n);
    ms.display();
    getch();
}

Output:

Explanation:

Merge sort animation video link:
https://www.youtube.com/watch?v=4VqmGXwpLqc

Program to illustrate Stack using Arrays in c++

 /*  stack array implementation using class and object in c++ */

#include<iostream.h>
#include<conio.h>
#include<process.h>
#include<iomanip.h>
#define max 20
int i,n,top=-1,a[max],item; /* global declaration*/

class rkstack
{
public:
int push(void); /* push function declaration */
int pop(void);  /* pop function declaration */
int display(void); /* display function declaration */
};


int rkstack::push() /* implementation function */
{
    if(top>=n-1)
    {
      cout<<"\n Stack overflow";
      return top;
    }
    cout<<"\n Enter the item to be added: ";
    cin>>item;
    top++;
    a[top]=item;
    return top;
 }

int rkstack::pop()
 {
    if(top<0)
    {
     cout<<"\n stack underflow";
     return top;
    }
    cout<<"\n The poped item from stack is "<<a[top];
    --top;
    return top;
}

int rkstack::display()
 {
    if(top<0)
     {
     cout<<"\n Stack is empty " ;
     return top;
     }
    cout<<"stack elements are:\n";
    for(i=top;i>=0;i--)
     cout<<a[i]<< "   ";
   cout<<"\n";
   return top;
 }

void main()
{
  int ch;
  rkstack s;
  clrscr();
  cout<<"\nEnter stack size :";
  cin>>n;
  while(1)
  {
    cout<<"\n****  MENU *** \n\n";
    cout<<"\n 1.PUSH  \n";
    cout<<"\n 2.POP  \n";
    cout<<"\n 3.DISPLAY  \n";
    cout<<"\n 4.QUIT  \n";
    cout<<"\n ENTER UR CHOICE: ";
    cin>>ch;
    switch(ch)
    {
       case 1:s.push();break;
       case 2:s.pop();break;
       case 3:s.display();break;
       case 4:exit(1);break;
       default:cout<<"u have entered wrong choice";break;
    }
  }
}

Output: 

/* stack array implementation with out using class and object in c++ */
#include<iostream.h>
#include<conio.h>
#include<process.h>
#include<iomanip.h>
#define max 20
int push(void); /* push function declaration */
int pop(void);  /* pop function declaration */
int display(void); /* display function declaration */
int i,n,top=-1,a[max],item; /* global declaration*/

void main()
{  
  int ch;
  clrscr();
  cout<<"\nEnter stack size :";
  cin>>n;
  while(1)
  {
    cout<<"\n****  MENU *** \n\n";
    cout<<"\n 1.PUSH  \n";
    cout<<"\n 2.POP  \n";
    cout<<"\n 3.DISPLAY  \n";
    cout<<"\n 4.QUIT  \n";
    cout<<"\n ENTER UR CHOICE: ";
    cin>>ch;
    switch(ch)
    {
       case 1:push();break;
       case 2:pop();break;
       case 3:display();break;
       case 4:exit(1);break;
       default:cout<<"u have entered wrong choice";break;
    }
  }
}
int push() /* implementation function */
{
    if(top>=n-1)
    {
      cout<<"\n Stack overflow";
      return top;
    }
    cout<<"\n Enter the item to be added: ";
    cin>>item;
    top++;
    a[top]=item;
    return top;
 }
 
int pop()
 {
    if(top<0)
    {
     cout<<"\n stack underflow";
     return top;
    }
    cout<<"\n The poped item from stack is "<<a[top];
    --top;
    return top;
}

int display()
 {
    if(top<0)
     {
     cout<<"\n Stack is empty " ;
     return top;
     }
    cout<<"stack elements are:\n";
    for(i=top;i>=0;i--)
     cout<<a[i]<< "   ";
   cout<<"\n";
   return top;
 }



ANIMATION VIDEO LINK OF STACK :
https://www.youtube.com/watch?v=-KQpk-dIA8s

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...