I am trying to implement matrix multiplication in c++. I found a sample code using a class that writes in .h
and .cpp
files. This is just a part of the code that related to my question:
#include "Matrix.h"
// Constructor - using an initialisation list here
Matrix::Matrix(int rows, int cols, bool preallocate): rows(rows), cols(cols), size_of_values(rows * cols), preallocated(preallocate)
{
// If we want to handle memory ourselves
if (this->preallocated)
{
// Must remember to delete this in the destructor
this->values = new double[size_of_values];
}
}
void Matrix::matMatMult(Matrix& mat_left, Matrix& output)
{
// The output hasn't been preallocated, so we are going to do that
output.values = new double[this->rows * mat_left.cols];
// Set values to zero before hand
for (int i = 0; i < output.size_of_values; i++)
{
output.values[i] = 0;
}
I wonder why they initialised using the output matrix with 0s output.values[i] = 0;
while it has been allocated memory before?
From cppreference on new
expression:
The object created by a new-expression is initialized according to the following rules:
- [...]
- If type is an array type, an array of objects is initialized.
- If initializer is absent, each element is default-initialized
- If initializer is an empty pair of parentheses, each element is value-initialized.
"default-initialized" int
s are colloquially not initialized. They have indeterminate values. The empty pair of parantheses refers to what Ted mentioned in a comment:
output.values = new double[this->rows * mat_left.cols]{};
Value initialization is described here. The case that applies here is
- otherwise, the object is zero-initialized.
I wonder why they initialised using the output matrix with 0s output.values[i] = 0; while it has been allocated memory before?
Allocating memory and initializing an object are two seperate steps. Yes, the elements have to be initialzed, allocating memory is not sufficient.