0

Usually, I tend to use explicit keyword in the constructor to avoid implicit conversion.

But when I try implement Matrix class, compile error happened in the operator*() function, it showed:

error: no matching constructor for initialization of 'Matrix', however, when I remove the explicit key word in the copy constructor, every thing goes well.

I know what explicit means, it means the parameter should be EXACTLY matched, when returning res in the operator*() function, the copy constructor will be called, I think the parameter is well matched, but why the error happened?

class Matrix {
private:
  vector<vector<int>> mat;
  int n;

public:
  explicit Matrix(int n): n(n) {
    this->mat.assign(n, vector<int>(n, 0));
  }

  explicit Matrix(const Matrix& obj) {
    this->n = obj.mat[0].size();
    this->mat = obj.mat;
  }

  Matrix operator*(const Matrix& rhs) {
    Matrix res(n);

    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < n; ++j) {
        for (int k = 0; k < n; ++k) {
          res.mat[i][j] += this->mat[i][k] * rhs.mat[k][j];
        }
      }
    }

    return res; // Compiler error here!
  }
};
ct.Liu
  • 139
  • 2
  • 9
  • 3
    s/default copy constructor/copy constructor/g – chris Jul 29 '14 at 13:46
  • It happens for the same reason returning `5` would give an error. No implicit conversion from `const Matrix &` to `Matrix` exists. I don't know what that has to do with matching parameters exactly. – chris Jul 29 '14 at 13:47
  • 1
    Why exactly do you want an explicit copy constructor? – Cameron Jul 29 '14 at 13:48
  • 1
    "I know what `explicit` means, it means the parameter should be EXACTLY matched" - no it doesn't. It means the constructor can't be used implicitly, which makes an explicit copy constructor rather useless. It makes sense for other single-argument constructors (like your first one), to prevent them being used for implicit conversions. – Mike Seymour Jul 29 '14 at 13:56

0 Answers0