OOP and Arrays

SO today I have started with Arrays. I have gotten this far with my code( Yes its random code but just practicing :> )
I now still need to do the following which confuses me because of the array part.

1) I need write implementation for the print function by derefernicing the memory address at the pointer + i which should print every character stored in 'blocks'.

2) The part that confuses me the most. Making a new class 'BigChocolate'
by modifying SmallChocolate (where SmallChocolate has a 1D dynamic array and BigChocolate a 2D dynamic array) where by dynamic I meanboth rows and columns must be specified at runtime.

//My header file
1
2
3
4
5
6
7
8
9
10
  class SmallChocolate {
private:
 int size;
 char *blocks;
public:
 SmallChocolate(int, char);
 ~SmallChocolate();
 void eat(int);
 void print() const;
};

// MY Implementation file

1
2
3
4
5
6
7
8
9
SMallChocolate::SmallChocolate(int s, char flavour){
size =s;
blocks = new char[size];
for (int i = 0; i<size; i++)
blocks[i] = flavour;
}

void SmallChocolate::eat(int blockNumber){
blocks[blockNumber] = 'x';


I know it is long but Please help couldnt find any online examples and I need to learn arrays other wise it just becomes a road block.
Anyone? Vlad?
1) do you mean cout << *(blocks + i);?

2)
Making a new class 'BigChocolate' by modifying SmallChocolate
what does that mean?
For (1), what does line 2 do here?
1
2
for (int i = 0; i<size; i++)
blocks[i] = flavour;



Note that your eat does not check whether blockNumber is valid, nor whether that block is still uneaten. You do have a destructor, don't you?

Your smallbar has one row of size blocks. (A const size would be logical.)

A largebar probably should have multiple rows, each with [code]size[code] blocks. R rows times C columns makes R*C blocks. Therefore, a smallbar with size == R*C has equal number of blocks, but it has only one index (blockNumber).

A largebar would want to eat a block from (row Y, column X). Sanity of eating from the middle of a bar is beyond us now. There are two obvious ways to 2D index:
1. Have a second array with pointers. Each pointer points to beginning of one row within a 1D array that holds all elements.
2. Compute the index. Block (X,Y) is the (Y*columns + X)th block in the 1D array.

If you do choose to use the second way, then BigChocolate could be implemented by having a SmallChocolate, rather than being a similar type.
Last edited on
@coder777: No actually implementing it in the implementation file, if you look its declared in the header file. And I mean just change SmallChocolate into a 2d array.

and @ Keskiverto Thank you very much got it solved and understand it.
Topic archived. No new replies allowed.