Trying to befriend a function of Derived in Base - Why doesn't it work?

71 views Asked by At

My first post here. I have two classes - Base and Derived (derived publicly from Base). In Derived, I have a function printAsFriend. Compiler is unhappy with this. Why? Methods in other classes can be befriended. Why doesn't it work with a derived class? It works OK if I remove the inheritance.

This works -

#include <iostream>
using namespace std;
class MyClass;
class YourClass{
    public:
    YourClass(){}
    void printAsFriend(MyClass m);
};
class MyClass{
    private: int i;
    public:
    MyClass(){}
    friend void YourClass::printAsFriend(MyClass m);
};
void YourClass::printAsFriend(MyClass m)
{ cout << m.i; }

int main(){
    return 0;
}

But this does not -

#include <iostream>
using namespace std;
class YourClass;
class MyClass{
    private: int i;
    public:
    MyClass(){}
    friend void YourClass::printAsFriend(MyClass m);
};
class YourClass:public MyClass{
    public:
    YourClass():MyClass(){}
    void printAsFriend(MyClass m);
};
void YourClass::printAsFriend(MyClass m)
{ cout << m.i; }

int main(){
    return 0;
}

I get the following error:

refFile.c:8:49: error: invalid use of incomplete type ‘class YourClass’ friend void YourClass::printAsFriend(MyClass m); ^ refFile.c:3:8: error: forward declaration of ‘class YourClass’ class YourClass; ^ refFile.c: In member function ‘void YourClass::printAsFriend(MyClass)’: refFile.c:5:16: error: ‘int MyClass::i’ is private private: int i; ^ refFile.c:16:14: error: within this context { cout << m.i; } ^

Why doesn't this work? What am I missing? Is it not allowed to befriend a function of your derived class?

1

There are 1 answers

1
Jonathan Potter On BEST ANSWER

It's nothing to do with friending the function, it's because you can't reference members of a class that you've only forward-declared.

In your second snippet, at the time MyClass is defined YourClass has only been forward-declared - the compiler hasn't seen the definition of it yet and so doesn't know that the member function printAsFriend even exists.