Jelmer Jelmer - 1 month ago 5
C++ Question

Class "classname" has no member "function"

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?

Answer

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