LearnFrenzy
Sign in Take a free test

Constructors and Destructors · Constructor Programs · Question 10

Matrix class with several constructors in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

Write a Matrix class with constructors for an r × c zero matrix, an n × n identity (via a static factory), and a nested initializer list, plus a multiply function and printing.

Solution
main.cpp
#include <initializer_list>
#include <iostream>
#include <vector>

class Matrix {
    std::size_t r_, c_;
    std::vector<double> a_;                         // row-major, rule of zero
public:
    Matrix(std::size_t r, std::size_t c) : r_(r), c_(c), a_(r * c, 0.0) {}
    Matrix(std::initializer_list<std::initializer_list<double>> rows)
        : Matrix(rows.size(), rows.begin()->size()) {
        std::size_t i = 0;
        for (const auto& row : rows) for (double v : row) a_[i++] = v;
    }
    static Matrix identity(std::size_t n) {
        Matrix m(n, n);
        for (std::size_t i = 0; i < n; ++i) m(i, i) = 1;
        return m;
    }
    double& operator()(std::size_t i, std::size_t j) { return a_[i * c_ + j]; }
    double operator()(std::size_t i, std::size_t j) const { return a_[i * c_ + j]; }
    Matrix operator*(const Matrix& o) const {
        Matrix m(r_, o.c_);
        for (std::size_t i = 0; i < r_; ++i)
            for (std::size_t k = 0; k < c_; ++k)
                for (std::size_t j = 0; j < o.c_; ++j) m(i, j) += (*this)(i, k) * o(k, j);
        return m;
    }
    void print() const {
        for (std::size_t i = 0; i < r_; ++i) {
            for (std::size_t j = 0; j < c_; ++j) std::cout << (*this)(i, j) << ' ';
            std::cout << '\n';
        }
    }
};

int main() {
    Matrix a{{1, 2}, {3, 4}};
    Matrix b{{0, 1}, {1, 0}};
    (a * b).print();
    std::cout << "--\n";
    (a * Matrix::identity(2)).print();
    return 0;
}

Output Verified by compiling and running

2 1 
4 3 
--
1 2 
3 4

The nested initializer_list constructor delegates to the (rows, cols) constructor for sizing, then fills the values. identity is a named static factory – clearer than another constructor overload. Storage is a std::vector, so no special members are needed.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links