I am having trouble with an assignment. I have a class called Grid and Record. Record is Grid that stores how many times each position in a Grid has been accessed. Grid must contain a data member of type Record that can store whenever a change is made to Grid. I’ve managed to avoid a circular dependancy, but I seem to have a problem with a “circular construction” leading to a stack overflow. Calling the Grid constructor makes a Record, which creates a Grid, which tries to make another Record and so on. My first thought was to make Grid’s Record data member a pointer which I initialize to NULL, then actually create the Record object outside of the constructor, however the assignment specifically says Grid’s Record data member must be of type Record, not a pointer to a Record. I am also not allowed to give Record a default constructor, so I’m guessing my implementation is wrong. Any suggestions for how I can solve this problem?
Record::Record(int rows, int cols) : grid(new Grid(rows, cols)) {};
Grid::Grid(int rows, int cols) : record(new Record(rows, cols)) {};
I think there is simply a misunderstanding in the assignment, or that it was written poorly.
It seems that what you want:
Which indicates that
ahas not been accessed anddhas been accessed twice.Now, if a
Gridshould contain aRecordto maintain its statistics, then aRecordcannot be aGrid. As you noticed it is circular. However,Recordis a grid. So I suspect there is a typo/reading issue here.My suggestion: