2

So I have a school project where I have to make a random dungeon crawler. I am quite new to C++ and I have an error, I know what the problem is but I don't know how to solve it exactly.

Here is the thing:

In my Chamber class I want a pointer to the DungeonLayer class. But I can't include DungeonLayer.h to Chamber.h because DungeonLayer.h already has Chamber.h included so I get an exception.

How can I make it so DungeonLayer class is accessable from the Chamber class?

Files:

DungeonLayer.h

#pragma once
#include <vector>
#include "Chamber.h"

class DungeonLayer {

public:
    DungeonLayer(std::string text, int l);
    Chamber findChamber(int x2, int y2);
    std::vector<Chamber> chambers;
    void generateDungeonLayer();
    bool chamberExists(int x2, int y2);
};

Chamber.h

#pragma once
#include <vector>
#include "Enemy.h"
#include "Hero.h"

class DungeonLayer {

};

class Chamber {

public:
    Chamber(std::vector<Chamber>* dungeonLayer, int ammountOfChambers);
    DungeonLayer *layer;
    Chamber *nextChamber;
    .......
    Chamber* Chamber::getNextChamber();
    void moveToChamber();

private:
    bool visited;
};

Whenever I set the pointer of the DungeonLayer (layer) and I want to call a function on it it gives the error:

Example

layer->findChamber(0,0);

Error:

"class "DungeonLayer" has no member "findChamber"   CPPAssessment   Chamber.cpp"

This is obvious because the class DungeonLayer in Chamber.h has nothing in it. But how can I make it so DungeonLayer is accessable from Chamber?

Jelmer
  • 949
  • 3
  • 10
  • 23
  • 2
    You have defined class `DungeonLayer` twice. If you wanted to forward-declare it, that's not how you do it. – krzaq Oct 22 '16 at 11:02
  • What do you mean? I have declared DungeonLayer in Dungeonlayer.h and in Chamber.h or? – Jelmer Oct 22 '16 at 11:08
  • No. http://stackoverflow.com/questions/1410563/what-is-the-difference-between-a-definition-and-a-declaration – krzaq Oct 22 '16 at 11:09
  • That's not helping, I am sorry but I am looking for an answer... – Jelmer Oct 22 '16 at 11:10

1 Answers1

2

If i have understood your problem correctly, this is the same problem as described in: Resolve header include circular dependencies.

It is called circular dependency. They both include each other. In this case, forward declare DungeonLayer in Chamber so it looks like this in chamber.h:

class DungeonLayer;


class Chamber {
public:
Chamber(std::vector<Chamber>* dungeonLayer, int ammountOfChambers);
DungeonLayer *layer;
Chamber *nextChamber;
.......
Chamber* Cha
}

this way you tell the compiler that it knows DungeonLayer, but it doesnt have to include it. To make calls to it you do need to know DungeonLayer. This can be archieved by including it in the chamber.cpp file. It should start with

#include "DungeonLayer.h"

And by the way, do not use C-style pointer when you have smart-pointers like shared_ptr

Community
  • 1
  • 1