Title: Accessing parent classes through composition
Tags: c++;class;composition
Question: In my program i have a very simple structure to represent a map in an RPG game. I have a Map class, with a 2d Array, "Grid", made out of Area objects, like so:
#pragma once
#include "Area.h"
class Map
public:
Map();
~Map();
Area Grid[10][10];
Then in the Map constructor:
Map75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0Map()
for (int y = 0; y < 10; y++) {
for (int x = 0; x < 10; x++) {
Grid[x][y] = Area();
I would like for the Area objects to be able to access certain values from the Map object, and I've read that i could include a reference to the map class when constructing the area object, so that it can refer back to its parent. But to do this, i would have to
#include "Map.h" in Area.h, which would create an include loop, and just not be very good in general. So how would i go about injecting a reference to the area's parent in each area object? Thanks for any help in advance.
Comment: You can declare functions or constructors that take references or pointers to forward-declared class objects.

Comment: Ok, I posted code as answer, you should be capable of making that into running program.

Comment: @skypjack I just want the Area objects to have a reference to the map they were created by so that they can access certain information from it, if that makes any sense.

Comment: Ok. How would I implement that in my example? I'm quite new to C++.

Comment: Yes, your solution is exactly what I was looking for, thanks.

Comment: It sounds like an XY-problem. What's exactly your goal?

Here is the accepted answer: // Area.h
#pragma once
struct Map;
struct Area {
Map* map = nullptr;
Area() {}
explicit Area( Map* m) : map(m) {}
Note that you may want to have some of the functions of Area defined in Area.cpp (that includes Map.h). I just left it out for simplicity of example code.
// Map.h
#pragma once
#include "Area.h"
struct Map
Map();
~Map();
Area Grid[10][10];
// Map.cpp
#include "Map.h"
Map75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0Map()
for (int y = 0; y < 10; y++) {
for (int x = 0; x < 10; x++) {
Grid[x][y] = Area(this);
}
Map75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0~Map() {}
// main.cpp
#include "Map.h"
int main()
Map m;
return 0;


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 6, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2017:00:11/05/17', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<c++><class><composition>', 'Title': 'Accessing parent classes through composition', 'ViewCount': 326, 'id': 47127298, 'user_AboutMe': '', 'user_AccountId': 12139614.0, 'user_DisplayName': 'James Mclaughlin', 'user_Reputation': 460.0, 'user_Views': 56.0, 'user_id': 8864013.0}}