I have simple class which you can see below:
Questions
- Can I have in my
Playgroundclass constructor like thisPlayground(int aRow, int aColumn);If YES how I must allocate memory in then case for elements of row and column ? If NO why ? - Why I can’t write
mPlayground[0][0] = 0and what can I do to do that ? If I can of course.
Playboard.h
#pragma once
#ifndef PLAYBOARD_H
#define PLAYBOARD_H
class Playground
{
public:
Playground()
{
}
};
class Playboard
{
public:
Playboard();
~Playboard();
private:
Playground** mPlayground;
int mRows;
int mColumns;
public:
void Initialize(int aRow, int aColumn);
};
#endif /** PLAYBOARD_H */
Playboard.cpp
#include "Playboard.h"
Playboard::Playboard()
{
mPlayground = 0;
}
void Playboard::Initialize(int aRow, int aColumn)
{
// Set rows and columns in order to use them in future.
mRows = aRow;
mColumns = aColumn;
// Memory allocated for elements of rows.
mPlayground = new Playground*[aRow];
// Memory allocated for elements of each column.
for (int i=0; i<aRow; i++)
mPlayground[i] = new Playground[aColumn];
}
Playboard::~Playboard()
{
// Free the allocated memory
for (int i=0; i<mRows; i++)
delete[] mPlayground[i];
delete[] mPlayground;
}
Yes, trivially:
You don’t have to allocate memory at all.
Playgroundcontains no pointers, and consequently requires no allocation.Because you haven’t overloaded the assignment operator for
Playground. For example,You cannot initialize members of the array with
new. You might be able to do this: