-1

I am confused about the following definition of the struct.

struct Matrix{
    int a, b;
    Matrix(int a =0, b = 0): a(a), b(b){} 
} m[26];

What does the statement "Matrix(int a =0, b = 0): a(a), b(b){} " mean and why we need it? Does "m[26]" means we define an array of Matrix?

one user
  • 99
  • 1
  • 1
    This question is mistagged: It has `c` but _not_ `c++`. The construct is a C++ construct. It is a "constructor". Edited the tags. – Craig Estey May 11 '22 at 14:53
  • Yes, `m[26]` means it's declaring an array of the structures. – Barmar May 11 '22 at 14:54
  • 1
    Perhaps a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) will be more useful here. – Jason May 11 '22 at 15:02

2 Answers2

0

The m[26] says to create an array of 26 of the struct Matrix type. That is fine in C.

However, the Matrix(int a=0, b==0): a(a), b(b) {} is specifying a constructor which assigns a and b parameters to a and b member variables in the struct Matrix is c++.

netskink
  • 4,033
  • 2
  • 34
  • 46
0
Matrix(int a = 0, b = 0) :
    a(a), b(b)
{
}

is a constructor with two parameters, a and b. They have default values, each being 0.

It initializes its member variables a and b with the provided arguments.

You can use it for example like this:

Matrix m1;         // initializes a and b with 0 each
Matrix m2(23);     //  initializes a and b with 23 and 0, respectively
Matrix m3(23, 42); //  initializes a and b with 23 and 42, respectively
the busybee
  • 10,755
  • 3
  • 13
  • 30