I've just recently learned about friend class
concept in C++ (I've googled around for a bit, but this answer made me laugh until I remembered the most important parts), and I'm trying to incorporate it in to the project I'm working on right now. The concise question is singled out in the end, but in general, I'm confused by complete lack of forward declarations in my working code.
All of my classes are separated through (sub-)folders and each one into a separate .h and .cpp file, but this should be enough to get a feeling about dependencies:
// FE.h - no implementations - no .cpp file
class FE
{
private:
virtual void somePrivateFunc() = 0;
// 90% virtual class, interface for further implementations
friend class TLS;
};
// DummyFE.h
#include "FE.h"
class DummyFE :: public FE {
/* singleton dummy */
private:
// constructor
public:
static DummyFE& instance();
};
// DummyFE.cpp
#include "DummyFE.h"
// all Dummy FE implementation
// ImplFE.h
#include "FE.h"
class ImplFE :: public FE { /* implemented */ };
// ImplFE.cpp
#include "FE.cpp"
// all Impl FE implementations
// SD.h - implements strategy design pattern
// (real project has more than just FE class in here)
#include "FE.h"
#include "DummyFE.h"
class SD
{
private:
FE &localFE;
public:
SD(FE ¶mFE = DummyFE::instance());
// ... and all the other phun stuff ...
friend class TLS;
};
// SD.cpp - implementations
# include "SD.h"
/* SD implemented */
// TLS.h - implements strategy design pattern
(on a higher level)
#include SD.h
class TLS{
private:
SD *subStrategy;
public:
void someFunctionRequiringFriendliness();
}
// TLS.cpp - implementations
#include "TLS.h"
void TLS::someFunctionRequiringFriendliness(){
this->subStrategy->localFE.somePrivateFunc(); // ok!
}
Now, I've had party getting all of this to actually compile with all the dependencies (had to write it down in to a class diagram in the end to make it work), but now it does. The fact that is actually confusing me, is that no forward declarations were needed. I know about forward declarations from before, and just in case, I refreshed my memory with this answer.
So, to try and keep it clear, my question:
When declaring the class TLS
as a friend, how come no explicit forward declarations were needed? Does that mean that a friend class
declaration is a forward declaration all in it self? For me, intuitively, something here is missing... And since it compiles and works normally, can somebody help correct my intuition? :D
PS sorry for such a lengthy introduction to the question and a bunch of code. Please, don't comment on my code concept - friends are good here, I'm pretty sure it's correct for my current project (it's just a bit hard to see from this skeleton). I'd just like to know why no forward declaration was needed anywhere.
See Question&Answers more detail:os