Search code examples
c++friend

Can't spot the mistake in using "friend" function of another class C++


Yes I know that private modifier created in order to prohibit access to class data
but isn't friend intended to allow special access to it?

Compiler:
main.cpp: In member function 'void C::blah(B&)':
main.cpp:48:26: error: 'int B::a' is private within this context
std::cout << obj.a << std::endl;

Everything below is implemented the way as it is in many tutorials.
May be it's just a silly mistake I made and blind to spot.

class C;

class B {
private:

    int a = 2;

public:

    friend void blah(B& obj);

};

class C {
public:

    void blah(B& obj) {
        std::cout << obj.a << std::endl;  //*
    }

};

*Member B::a is inaccessible


Solution

  • You're declaring a non-member function named blah, but not C::blah as friend.

    You could change your code to the following, and note the order of the declaration and definition.

    class B;
    
    class C {
    public:
        void blah(B& obj);
    };
    
    class B {
    private:
        int a = 2;
    public:
        friend void C::blah(B& obj);
    };
    
    void C::blah(B& obj) {
        std::cout << obj.a << std::endl;
    }
    

    LIVE