So I've encountered some problem in C++ (my first programming language was C).
Let's say I have the following classes:
2 headers (rectangle and grid, assume that point class is fine and another assumption is that we don't need print functions currently)
Grid.h
#ifndef GRID_H
#define GRID_H
#ifndef RECT_H
#include "Rectangle.h"
#endif
class Grid
{
public:
Grid(int tileW, int tileH, int width, int height, int color);
~Grid();
Rectangle& getRectAt(const Point &p);
void print() const;
private:
int count;
Rectangle **recs;
};
#endif
Rect.h
#ifndef RECT_H
#define RECT_H
#ifndef POINT_H
#include "Point.h"
#endif
class Rectangle
{
public:
Rectangle(int l, int u, int w, int h, int color);
int getColor() const;
void setColor(int color);
bool contains(const Point &p) const;
void print() const;
private:
const Point topLeft, bottomRight;
int color;
};
#endif
and the 2 cpp's:
Rect.cpp
#include "Rectangle.h"
Rectangle::Rectangle(int l, int u, int w, int h, int color) : topLeft(l, u), bottomRight(l + w, u + h) { this->color = color; }
int Rectangle::getColor() const
{
return this->color;
}
void Rectangle::setColor(int color)
{
this->color = color;
}
bool Rectangle::contains(const Point &p) const
{
return (this->topLeft.getX < p.getX && p.getX < this->bottomRight.getX
&& this->bottomRight.getY < p.getY && p.getY < this->bottomRight.getY);
}
void Rectangle::print() const
{
/**/
}
Grid.cpp
#include "Grid.h"
Grid::Grid(int tileW, int tileH, int width, int height, int color)
{
int index, index_c=0;
recs = new Rectangle *[width];
for (int index = 0; index < width; index++)
{
recs[index] = new Rectangle [height];
}
}
(assume that we don't need the other Grid functions and the constructor isn't finished).
Now what I'm trying to do is this, in Grid.cpp constructor, I'm trying to
dynamically allocate the Array of Arrays but I just can't understand the logic behind the memory allocation of classes in cpp.
I would appreciate if some one could explain me how the 'new' functions in cpp on classes and on n-dimensional arrays (of classes and in general).
I hope you understood the problem that I encounter here.
Thanks in advance.