Search code examples
c++friend

Sharing friends between classes via include file


I have some old c++ code where friend classes are all declared outside of a class in a bare include file. The include file is then shared between different classes Such as follows

IncludeFriends.h

#pragma once
friend class Friend1;// Error E0239
friend class Friend2;// Error E0239

friends.h

#pragma once
class Friend1
{
public:
    Friend1() {};
private:
    int pF1{0};
};

class Friend2
{
public:
    Friend2() {};
private:
    int pF2{0};
};

classes.h

#pragma once
#include "Friends.h"
class Class1
{
#include "IncludeFriends.h"
public:
    Class1() {};
    int getFriendInt(Friend1& f1) { return f1.pF1; };
};

class Class2
{
#include "IncludeFriends.h"
public:
    Class2() {};
    int getFriendInt(Friend2& f2) { return f2.pF2; };
};

I get the following errors:

1>------ Build started: Project: friendsTest, Configuration: Debug Win32 ------
1>classes.cpp
1>D:\friendsTest\classes.h(8,43): error C2248: 'Friend1::pF1': cannot access private member declared in class 'Friend1'
1>D:\friendsTest\Friends.h(7): message : see declaration of 'Friend1::pF1'
1>D:\friendsTest\Friends.h(2): message : see declaration of 'Friend1'
1>D:\friendsTest\classes.h(16,43): error C2248: 'Friend2::pF2': cannot access private member declared in class 'Friend2'
1>D:\friendsTest\Friends.h(15): message : see declaration of 'Friend2::pF2'
1>D:\friendsTest\friendsTest\Friends.h(10): message : see declaration of 'Friend2'
1>friendsTest.cpp
1>Generating Code...
1>Done building project "friendsTest.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

my editor also issues an additional complaint for the IncludeFiles.h file. It states: E0239 invalid specifier outside class declaration

and so on for n amount of classes and friend classes. This is no longer allowed in c++. I tried encapsulating the friend classes in another class that is itself declared as a friend in all the class definitions, but I read this will not work since there is no such thing as inheritance for friend classes, right? I was wondering if there is some workaround. I really dont want to write in all of the friends for each class since that would make my code way less readable. Thanks in advance!

EDIT: Since some have remarked that the general approach taken here is not the most sensible, maybe an alternative would be better than having to fix the actual problem.


Solution

  • A better way to solve this error is to use a macro. As shown below:

    #define FRIENDS \
        friend class Friend1; \
        friend class Friend2;
    

    and then replacing #include "IncludeFriends.h" with FRIENDS inside of the class declaration.