Using C++ implement class with dynamic memory allocation using constructor,destructor and copy constructor.Algorithm



https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJfShSmc4uzJ32B_Cnh6KDE7EeSGsUpqwnmXpsZMSrMSp0wjgo7gGWZu_JIDHC_zUiWwWkPBhm3Pz_vS0k-tjHPGbd4J7sxNkEVv5q-YbMtId0PtXLQqi2n_k4Dee10jKN6F-IOkz4Wqgg/s1600/c+and+c%252B%252B+meansofmine.jpg
Implement class with dynamic memory allocation.
Aim
     To implement class with dynamic memory allocation using constructor,destructor and copy constructor.Algorithm

Algorithm

Step 1: Start the Program Execution
Step 2: Create the Classes and declare all the Variables and Member functions.
Step 3: Using the classes with dynamic memory alloction.
Step 4: Create the class name as MATRIX.
Step 5: Declare the data member and member function.
Step 6: Declare constructor,destructor and copy constructor
Step 7: Display the result.
Step 8: Stop the Program Execution.

Program:
#include<iostream.h>
#include<conio.h>
class matrix
{
int **m;
int row,col;
public:
matrix()
{
row=col=0;
m=NULL;
}
matrix(int r,int c);
~matrix();
void getmatrix();
void showmatrix();
matrix(matrix &m2);
matrix &operator=(matrix &m2);
};
matrix::~matrix()
{
for(int i=0;i<row;i++)
delete m[i];
delete m;
}
matrix::matrix(int r,int c)
{
row=r;
col=c;
m=new int *[row];
for(int i=0;i<row;i++)
m[i]=new int[col];
}
matrix::matrix(matrix &m2)
{
cout<<"\n  Copy constructor invoked....\n";
row=m2.row;
col=m2.col;
m=new int*[row];
for(int i=0;i<row;i++)
m[i]=new int[col];
for(i=0;i<row;i++)
for(int j=0;j<row;j++)
m[i][j]=m2.m[i][j];
}
matrix &matrix::operator=(matrix &m2)
{
cout<<"\n Assignment operator overloading....\n" ;
row=m2.row;
col=m2.col;
m=new int*[row];
for(int i=0;i<row;i++)
m[i]=new int[col];
for(i=0;i<row;i++)
for(int j=0;j<row;j++)
m[i][j]=m2.m[i][j];
return *this;
}
void matrix::getmatrix()
{
int i,j;
for(i=0;i<row;i++)
for(j=0;j<col;j++)
cin>>m[i][j];
}
void matrix::showmatrix()
{
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
cout<<"\t"<<m[i][j];
cout<<"\n";
}
}
void main()
{
int r,c;
clrscr();
cout<<"\nEnter the no of rows and columns.....\n";
cin>>r>>c;
matrix m1(r,c);
cout<<"Enter the matrix elements....\n";
m1.getmatrix();
cout<<"\nThe entered mjatrix is..............\n";
m1.showmatrix();
matrix m2=m1;
cout<<"\nThe resultant matrix is....\n";
m2.showmatrix();
matrix m3;
m3=m1;
cout<<"\nResult of assignment operator overloading.....\n";
m3.showmatrix();
getch();
}

0 comments:

Post a Comment