Skip to main content

Matrix addition by overloading +

Short answer

Overload + as member function: create a new Matrix, sum corresponding elements of the calling matrix and the argument, return result. Both matrices must have identical rows and columns. Usage: m3 = m1 + m2.

Write a program to add two matrices by overloading the + operator.

The + operator is overloaded as a member function of class Matrix. The left matrix is the calling object and the right matrix is the argument. The result is a new matrix whose element [i][j] is the sum of the corresponding elements. Both matrices must have the same order (rows and columns).

#include <iostream>
using namespace std;

class Matrix {
    int a[10][10];
    int r, c;
public:
    void read() {
        cout << "Enter rows and columns: ";
        cin >> r >> c;
        cout << "Enter " << r * c << " elements:" << endl;
        for (int i = 0; i < r; i++)
            for (int j = 0; j < c; j++)
                cin >> a[i][j];
    }

    Matrix operator+(Matrix m) {
        Matrix t;
        t.r = r;
        t.c = c;
        for (int i = 0; i < r; i++)
            for (int j = 0; j < c; j++)
                t.a[i][j] = a[i][j] + m.a[i][j];
        return t;
    }

    void display() {
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++)
                cout << a[i][j] << "\t";
            cout << endl;
        }
    }
};

int main() {
    Matrix m1, m2, m3;
    cout << "First matrix" << endl;
    m1.read();
    cout << "Second matrix" << endl;
    m2.read();
    m3 = m1 + m2;                 // m1.operator+(m2)
    cout << "Sum of matrices:" << endl;
    m3.display();
    return 0;
}

Sample run (2 x 2):

First matrix
Enter rows and columns: 2 2
Enter 4 elements:
1 2 3 4
Second matrix
Enter rows and columns: 2 2
Enter 4 elements:
5 6 7 8
Sum of matrices:
6	8
10	12

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 5 questions →