Dynamic Allocation & Copy Constructor

Program in C++ to Create a Matrix using Dynamic allocation and copying it to another object using copy constructor and deallocate the memory using ‘delete’ key word.

Program:

#include<iostream>
#include<new>                                    //Header file for new
using namespace std;

class Matrix
{
int m,n;
int**p;                                   //Pointer to pointer(which stores the address of another pointers)

 public:

 Matrix()           //dynamic constructor
{
 cout<<"Enter no of rows and columns:";
 cin>>m>>n;                                      // Dynamic Allocation
p=new int*[m];                                   //rows
for(int i=0;i<m;i++)
p[i]=new int[n];                                 //in each row no of columns
int i,j;
cout<<"Enter values for the matrix";
for(i=0;i<m;i++)
 {
 for(j=0;j<n;j++)
{
 cin>>p[i][j];
}
}
  }

Matrix(Matrix &u)     // copy constructor
{
m=u.m;
n=u.n;
p=new int*[m];
for(int i=0;i<m;i++)
 p[i]=new int[n];
int i,j;
for(i=0;i<m;i++)
 {
for(j=0;j<n;j++)
  {
p[i][j]=u.p[i][j];
  }
 }
}



void add(Matrix f1)
{
cout<<"Addition of above two matrices:";
int i,j;
for(i=0;i<m;i++)
  {
for(j=0;j<n;j++)
   {
  cout<<p[i][j]+f1.p[i][j]<<" ";        //Displayed added matrix directly
   }
cout<<"\n";
  }
delete(p);
delete(f1.p);
}


 void dis()
 {
cout<<"Matrix: \n";
int i,j;
for(i=0;i<m;i++)
 {
  for(j=0;j<n;j++)
   {
   cout<<p[i][j];
   }
  cout<<endl;
  }
 }
};



int main()
{

Matrix m1;                // first object which invokes dynamic constructor
cout<<"\nFirst Object copy is:\n";
m1.dis();
Matrix m2(m1);            // Second object is same copy of fiest object using copy constructor
cout<<"\nSecond Object copy is:\n";
m2.dis();
cout<<"\nAddition of Same copies is:\n";
m1.add(m2);
return 0;
}


Comments

Popular posts from this blog

Refrigeration By ice cutting.

How to check if you're buying a stolen phone.

Life after Chernobyl