Skip to main content

Matrix multiplication by overloading *

Short answer

For 3×3 Matrix, overload * as member: initialize each element C[i][j] = 0, then sum over k (0 to 2) of A[i][k] * B[k][j]. Return the new Matrix. Usage: C = A * B.

Develop a program using a class with 3×3 matrix as a data member. Overload the * operator so as to multiply two matrices.

The class Matrix keeps a 3 x 3 array as its data member. The * operator is overloaded as a member function: for the product C = A * B, each element is C[i][j] = Σ A[i][k] * B[k][j] for k = 0 to 2.

#include <iostream>
using namespace std;

class Matrix {
    int m[3][3];
public:
    void read() {
        cout << "Enter 9 elements (row-wise):" << endl;
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++)
                cin >> m[i][j];
    }

    Matrix operator*(Matrix b) {
        Matrix c;
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++) {
                c.m[i][j] = 0;
                for (int k = 0; k < 3; k++)
                    c.m[i][j] += m[i][k] * b.m[k][j];
            }
        return c;
    }

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

int main() {
    Matrix a, b, c;
    cout << "Matrix A" << endl;  a.read();
    cout << "Matrix B" << endl;  b.read();
    c = a * b;                    // a.operator*(b)
    cout << "A * B =" << endl;
    c.display();
    return 0;
}

Sample run: with A = [1 2 3; 4 5 6; 7 8 9] and B = identity matrix, the output is

A * B =
1	2	3
4	5	6
7	8	9

With B = [1 1 1; 1 1 1; 1 1 1] the output is rows 6 6 6, 15 15 15, 24 24 24.

Note: matrix multiplication is not commutative, so the order of the operands matters: the left operand is the invoking object.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 5 questions →