Search code examples
c++classcomposition

Accessing parent classes through composition


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:

 Map::Map()
 {
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.


Solution

  • // 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"
    
    Map::Map()
    {
        for (int y = 0; y < 10; y++) {
            for (int x = 0; x < 10; x++) {
                Grid[x][y] = Area(this);
            }
        }
    }
    
    Map::~Map() {}
    
    // main.cpp
    #include "Map.h"
    int main()
    {
        Map m;
        return 0;
    }