constructors and destructors C++ program - Computer Programming

Latest

C C++ Java Python Perl Programs Examples with Output -useful for Schools & College Students

Thursday, August 31, 2017

constructors and destructors C++ program

Write a C++ program to demonstrate the use of constructors and destructors




Program:
#include<iostream.h>
class Arr
{
int m,n;
int **a;
public:
Arr(int x,int y);
Arr(Arr &c){a=c.a;m=c.m;n=c.n;}
void getd();
void shd();
~Arr()
{delete a;}
};

Arr::Arr(int x,int y)
{
m=x;
n=y;
a=new int*[m];
for(int i=0;i<m;i++)
a[i]=new int[n];
}

void Arr::getd()
{
int j;
cout<<"\nEnter the matrix elements:";
for(int i=0;i<m;i++)
for(j=0;j<n;j++)
cin>>a[i][j];
}

void Arr::shd()
{
int j;
cout<<"\n\nMatrix elements:\n";
for(int i=0;i<m;i++){
for(j=0;j<n;j++)
cout<<a[i][j]<<" ";
cout<<endl;}
}

int main()
{
int m,n;
cout<<"Enter the size of matrix needed:";
cin>>m>>n;
Arr t(m,n),s(t);
cout<<"By help of constructor:";
t.getd();
t.shd();
cout<<"By help of copy constructor:";
s.shd();
s.getd();
s.shd();
return 0;

}

SAMPLE INPUTS & OUTPUTS:

Enter the size of matrix needed: 2 2
By help of constructor:
Enter the matrix elements:
1  2
3  4
Matrix Elements
1 2
3 4
By help of copy constructor:
Matrix Elements
1 2
3 4
Enter the matrix elements:
1 2
3 4
Matrix Elements
2 3
2 4

No comments:

Post a Comment