Experiment 2
Aim
To implement a Matrix class with dynamic memory
allocation and provide a proper constructor, destructor, copy constructor,
and overloaded assignment operator.
Objectives
- To
understand dynamic memory allocation.
- To
implement a dynamically allocated Matrix class.
- To
understand the copy constructor.
- To
implement the assignment operator.
- To
understand proper memory deallocation using a destructor.
Theory
When memory is allocated dynamically using new, it must be
explicitly released using delete or delete[].
A class that manages dynamically allocated memory should
properly implement:
- Constructor
- Destructor
- Copy
constructor
- Copy
assignment operator
This is commonly referred to as the Rule of Three.
Algorithm
- Create
a Matrix class containing rows, columns and dynamically allocated memory.
- Allocate
memory using new.
- Initialize
the matrix through the constructor.
- Implement
the copy constructor to perform a deep copy.
- Overload
the assignment operator.
- Implement
the destructor to release allocated memory.
- Display
the matrices.
Program
#include <iostream>
using namespace std;
class Matrix {
int rows, cols;
int **a;
public:
Matrix(int r, int
c) {
rows = r;
cols = c;
a = new
int*[rows];
for (int i =
0; i < rows; i++)
a[i] = new
int[cols];
cout <<
"Enter matrix elements:\n";
for (int i =
0; i < rows; i++)
for (int j
= 0; j < cols; j++)
cin
>> a[i][j];
}
Matrix(const
Matrix &m) {
rows = m.rows;
cols = m.cols;
a = new
int*[rows];
for (int i =
0; i < rows; i++) {
a[i] = new
int[cols];
for (int j = 0; j < cols; j++)
a[i][j] = m.a[i][j];
}
}
Matrix&
operator=(const Matrix &m) {
if (this !=
&m) {
for (int i
= 0; i < rows; i++)
delete[] a[i];
delete[]
a;
rows =
m.rows;
cols =
m.cols;
a = new
int*[rows];
for (int i
= 0; i < rows; i++) {
a[i] =
new int[cols];
for
(int j = 0; j < cols; j++)
a[i][j]
= m.a[i][j];
}
}
return *this;
}
void display() {
for (int i =
0; i < rows; i++) {
for (int j
= 0; j < cols; j++)
cout
<< a[i][j] << " ";
cout
<< endl;
}
}
~Matrix() {
for (int i =
0; i < rows; i++)
delete[]
a[i];
delete[] a;
}
};
int main() {
Matrix A(2, 2);
cout <<
"\nOriginal Matrix:\n";
A.display();
Matrix B = A;
cout << "\nCopy
Constructor Matrix:\n";
B.display();
Matrix C(2, 2);
C = A;
cout <<
"\nAssignment Operator Matrix:\n";
C.display();
return 0;
}
Result
Thus, the Matrix class was successfully implemented using dynamic
memory allocation, constructor, destructor, copy constructor and overloaded
assignment operator.
Viva Questions
- What
is dynamic memory allocation?
- What
is a copy constructor?
- What
is deep copying?
- What
is the purpose of a destructor?
- What
is the difference between copy constructor and assignment operator?
- What
is the Rule of Three?
No comments:
Post a Comment