I'm starting to learn C++ and recently encountered a problem with circular dependency of two headers.
I've already tried forward declaring the Class and namespace, also played around with it in a seperate project but didn't find any solution. Whatever I do the function doesn't get access to the class private members.
Here i simplified the problem a little bit.
#pragma once
#include "B.h"
class Player {
private:
int m_number;
public:
friend void Byte::getDataChunk(Player& p);
};
#pragma once
#include <iostream>
#include "A.h"
class Player;
namespace Byte {
void doOtherStuff() {
//other Stuff
}
void getDataChunk(Player& p) {
std::cout << p.m_number;
doOtherStuff();
}
}
I would really like to keep the class and namespace in seperate files, but I don't see any way of doing it.
Thanks for your help in advance!
You need to change A.h
to include a forward declaration of getDataChunk()
in namespace Byte
:
#pragma once
#include "B.h"
class Player;
namespace Byte {
void getDataChunk(Player& p);
}
class Player {
private:
int m_number;
public:
friend void Byte::getDataChunk(Player& p);
};
Please note also that including function definitions in header files (i.e. getDataChunk()
in B.h
) is going to cause you headaches.