Friday, 22 March 2019

CPP-EX34

C++ PROGRAM Program to explain Constructor, Destructor, Copy constructor and Assignment operator overloading

#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); //copy constructor
            matrix& operator=(matrix &m2);

};

matrix::~matrix()
{
            for(int i=0;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
            m[i]=new int[col];
}

matrix::matrix(matrix &m2)
{
            cout<<"\nCopy 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<<"\nAssignment 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()

{
            for(int i=0;i
            for(int j=0; j
                        cin>>m[i][j];
}

void matrix::showmatrix()

{
            for(int i=0;i
            {
                        for(int j=0;j
                                    cout<<"\t"<
                                    cout<<"\n";
            }

}

void main()

{
            int r,c;
            clrscr();
            cout<<"\nEnter rows and columns of the matrix:\n";
            cin>>r>>c;
            matrix m1(r,c);
            cout<<"\nEnter the matrix elements one by one:\n";
            m1.getmatrix();
            cout<<"\nEntered matrix is:\n";
            m1.showmatrix();
            //invoking copy constructor
            matrix m2=m1;
            cout<<"\nResult of the copy constructor is:\n";
            m2.showmatrix();
            matrix m3;
            m3=m1;
            cout<<"\nResult of assignment operator overloading:\n";
            m3.showmatrix();
            getch();
}