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

Algorithm:
Step 1: Create a class
Step 2: Create a constructor for this class which will set the value of its member variables.
Step 3: Create the other required methods for the given class
Step 4: Define the destructor.
Step 5: Create an object of this class
Step 6: The constructor will be called upon creation and when the program is ending the destructor will be called.

Program Code:
#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;
}


Output:
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 2
3 4
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: