Search code examples
c++inheritancefriend

How can I friend a derived class function in the base class?


I have the following code:

#include <iostream>

class A {
    private:
        int a;
    public:
        void setA(int a_);
    friend int B::getA();
};

class B : public A {
    public:
        int getA();
};

void A::setA(int a_) {
    a = a_;
}

int B::getA() {
    return a;
}

int main() {
    B myB;
    myB.setA(9);

    std::cout << myB.getA()<< std::endl;
    return 0;
}

Compiling with g++ yields:

friend.cpp:10:16: error: use of undeclared identifier 'B'
    friend int B::getA();

My thinking is that when the compiler is going through the class A definition, it does not yet know about class B. Therefore, I can forward declare B to take care of this problem:

#include <iostream>

class B;

class A {
...

That doesn't quite work:

friend.cpp:10:16: error: incomplete type 'B' named in nested name specifier
    friend int B::getA();

It looks like the compiler isn't able to resolve the function as it is given.

How can I make a derived class function a friend in the base class?


Solution

  • Your code seems to violate the basic concept of data encapsulation. To resolve it, either make A::a protected, as @rici suggested, or define a getter in class A.

    class A {
    private:
       int a;
    public:
       void setA(int a_);
       virtual int getA();
    };
    
    class B : public A {
    public:
       int getA();
    };
    
    void A::setA(int a_) {
       a = a_;
    }
    int A::getA() {
       return a;
    }
    
    int B::getA() {
       return A::getA();
    }