CJCoding With Joseph
15free / daySign inCreate account

Grid Matrix: operator() Over a Single Heap Buffer

Write a class Grid that stores a rows x cols matrix of ints in ONE dynamically allocated block (not an array of arrays) and exposes its elements through operator(). Do NOT write a main function; a hidden test provides one.

Required members:
- Grid(int rows, int cols) - allocates rows * cols ints with new[], every element 0.
- ~Grid() - releases the block.
- int& operator()(int r, int c) - returns a REFERENCE.
- int operator()(int r, int c) const - the read-only version, used through a const Grid&.
- int rows() const and int cols() const.

Element (r, c) lives at index r * cols + c of the block (row-major order).

Free the memory you allocate - this question checks for memory leaks.

The hidden test reads rows and cols, prints the dimensions and the starting value of (0, 0), reads rows * cols numbers into the grid, prints it one row per line with single spaces, prints the sum of every element, then multiplies (0, 0) by 10 and prints it. It hands the grid to a helper taking a const Grid&, so BOTH operator() overloads are required.

For the input:
2 3
1 2 3
4 5 6

your class must produce exactly the output shown in Expected Output.

Expected Output:

2x3 start 0
1 2 3
4 5 6
sum=21
scaled=10

= newline. The output ends with a newline — print one after the last line.

Hints4 available
Topics:
Pointers
📥 Auto-Input:
2 3\n1 2 3\n4 5 6\n
This input is automatically fed to your program's stdin
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (cout, fori)

Your Output

Run your code to see the output here...

Test Cases

Run your code to see test case results.